From 51baabd760922d3cc2f75a327d442b8ac95e780b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 30 Sep 2022 17:58:17 -0500 Subject: clean up a bit --- src/slskd/Shares/ShareRepository.cs | 479 ++++++++++++++++++++++++------------ src/slskd/Shares/ShareScanner.cs | 10 +- src/slskd/Shares/ShareService.cs | 8 +- 3 files changed, 333 insertions(+), 164 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs index c01c9d83..ba4b714c 100644 --- a/src/slskd/Shares/ShareRepository.cs +++ b/src/slskd/Shares/ShareRepository.cs @@ -25,136 +25,137 @@ namespace slskd.Shares using Serilog; using Soulseek; + /// + /// Persistent storage of shared files and metadata. + /// public interface IShareRepository { - int CountDirectories(string prefix = null); - int CountFiles(string prefix = null); - void CreateTables(bool discardExisting = false); - bool TryValidateTables(string connectionString); - void InsertDirectory(string name, long timestamp); - void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, Soulseek.File file, long timestamp); - long DeleteDirectories(long olderThanTimestamp); - long DeleteFiles(long olderThanTimestamp); - IEnumerable ListDirectories(string prefix = null); - IEnumerable ListFiles(string directory = null, bool includeFullPath = false); - void Backup(string destinationConnectionString); - void Restore(string sourceConnectionString); - string FindOriginalFilename(string maskedFilename); - IEnumerable Search(SearchQuery query); - } - - public class ShareRepository : IShareRepository - { - public ShareRepository(string connectionString) - { - ConnectionString = connectionString; - } + /// + /// Backs the current database up to the database at the specified . + /// + /// The connection string of the destination database. + void BackupTo(string connectionString); - private string ConnectionString { get; } + /// + /// Counts the number of directories in the database. + /// + /// The optional directory prefix used for counting subdirectories. + /// The number of directories. + int CountDirectories(string parentDirectory = null); - private SqliteConnection GetConnection(string connectionString = null) - { - connectionString ??= ConnectionString; + /// + /// Counts the number of files in the database. + /// + /// The optional directory prefix used for counting files in a subdirectory. + /// The number of files. + int CountFiles(string parentDirectory = null); - var conn = new SqliteConnection(connectionString); - conn.Open(); - return conn; - } + /// + /// Creates a new database. + /// + /// + /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case + /// tables are explicitly dropped prior to creation. + /// + /// An optional value that determines whether the existing database should be discarded. + void Create(bool discardExisting = false); /// - /// Searches the cache for the specified and returns the matching files. + /// Finds the filename of the file matching the specified . /// - /// The query for which to search. - /// The matching files. - public IEnumerable Search(SearchQuery query) - { - string Clean(string str) => str.Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " ") - .Replace("'", "''"); + /// The fully qualified remote path of the file. + /// The filename, if found. + string FindFilename(string maskedFilename); - var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); - var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); + /// + /// Inserts a directory. + /// + /// The fully qualified local name of the directory. + /// The timestamp to assign to the record. + void InsertDirectory(string name, long timestamp); - var sql = $"SELECT files.maskedFilename, files.code, files.size, files.extension, files.attributeJson FROM filenames " + - "INNER JOIN files ON filenames.maskedFilename = files.maskedFilename " + - $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}' " + - "ORDER BY filenames.maskedFilename ASC;"; + /// + /// Inserts a file. + /// + /// The fully qualified remote path of the file. + /// The fully qualified local path of the file. + /// The timestamp at which the file was last modified, according to the host OS. + /// The Soulseek.File instance representing the file. + /// The timestamp to assign to the record. + void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, Soulseek.File file, long timestamp); - var results = new List(); - SqliteDataReader reader = default; + /// + /// Lists all directories. + /// + /// The optional directory prefix used for listing subdirectories. + /// The list of directories. + IEnumerable ListDirectories(string parentDirectory = null); - try - { - using var conn = GetConnection(); - using var cmd = new SqliteCommand(sql, conn); - reader = cmd.ExecuteReader(); + /// + /// Lists all files. + /// + /// The optional parent directory. + /// A value indicating whether the fully qualified path should be returned. + /// The list of files. + IEnumerable ListFiles(string parentDirectory = null, bool includeFullPath = false); - while (reader.Read()) - { - var filename = reader.GetString(0); - var code = reader.GetInt32(1); - var size = reader.GetInt64(2); - var extension = reader.GetString(3); - var attributeJson = reader.GetString(4); + /// + /// Deletes directory records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete directories. + /// The number of records deleted. + long PruneDirectories(long olderThanTimestamp); - var attributeList = attributeJson.FromJson>(); + /// + /// Deletes file records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete files. + /// The number of records deleted. + long PruneFiles(long olderThanTimestamp); - var file = new Soulseek.File(code, filename, size, extension, attributeList); - results.Add(file); - } + /// + /// Restores the current database from the database at the specified . + /// + /// The connection string of the source database. + void RestoreFrom(string connectionString); - return results; - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); - return Enumerable.Empty(); - } - } + /// + /// Searches the database for files matching the specified . + /// + /// The search query. + /// The list of matching files. + IEnumerable Search(SearchQuery query); + } - public string FindOriginalFilename(string maskedFilename) + /// + /// Persistent storage of shared files and metadata. + /// + public class ShareRepository : IShareRepository + { + /// + /// Initializes a new instance of the class. + /// + /// + public ShareRepository(string connectionString) { - using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn); - cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); - - var reader = cmd.ExecuteReader(); - - if (!reader.Read()) - { - Log.Warning("Failed to resolve shared file {Filename}", maskedFilename); - return null; - } - - var resolved = reader.GetString(0); - Log.Debug($"Resolved requested shared file {maskedFilename} to {resolved}"); - return resolved; + ConnectionString = connectionString; } - public void CreateTables(bool discardExisting = false) - { - using var conn = GetConnection(); - - conn.ExecuteNonQuery("PRAGMA journal_mode=WAL"); + private string ConnectionString { get; } - if (discardExisting) + /// + /// Attempts to validate the database at the specified . + /// + /// The connection string of the database to validate. + /// A value indicating whether the database is valid. + /// Thrown if no connection string is provided. + public static bool TryValidateDatabase(string connectionString) + { + if (connectionString == null) { - conn.ExecuteNonQuery("DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;"); + throw new ArgumentNullException(nameof(connectionString), "A connection string is required"); } - conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL);"); - - conn.ExecuteNonQuery("CREATE VIRTUAL TABLE IF NOT EXISTS filenames USING fts5(maskedFilename);"); - - conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS 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, timestamp INTEGER NOT NULL);"); - } - - public bool TryValidateTables(string connectionString) - { var schema = new Dictionary() { { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, @@ -166,7 +167,9 @@ namespace slskd.Shares { Log.Debug("Validating shares database with connection string {String}", connectionString); - using var conn = GetConnection(connectionString); + using var conn = new SqliteConnection(connectionString); + conn.Open(); + 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(); @@ -206,21 +209,23 @@ namespace slskd.Shares } } - public void Backup(string destinationConnectionString) + /// + /// Backs the current database up to the database at the specified . + /// + /// The connection string of the destination database. + public void BackupTo(string connectionString) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(destinationConnectionString); + using var backupConn = GetConnection(connectionString); sourceConn.BackupDatabase(backupConn); } - public void Restore(string sourceConnectionString) - { - using var sourceConn = GetConnection(sourceConnectionString); - using var restoreConn = GetConnection(); - sourceConn.BackupDatabase(restoreConn); - } - - public int CountDirectories(string prefix = null) + /// + /// Counts the number of directories in the database. + /// + /// The optional directory prefix used for counting subdirectories. + /// The number of directories. + public int CountDirectories(string parentDirectory = null) { using var conn = GetConnection(); @@ -228,14 +233,14 @@ namespace slskd.Shares try { - if (string.IsNullOrEmpty(prefix)) + if (string.IsNullOrEmpty(parentDirectory)) { cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn); } else { cmd = new SqliteCommand("SELECT COUNT(*) FROM directories WHERE name LIKE @prefix || '%'", conn); - cmd.Parameters.AddWithValue("prefix", prefix); + cmd.Parameters.AddWithValue("prefix", parentDirectory); } var reader = cmd.ExecuteReader(); @@ -248,7 +253,12 @@ namespace slskd.Shares } } - public int CountFiles(string prefix = null) + /// + /// Counts the number of files in the database. + /// + /// The optional directory prefix used for counting files in a subdirectory. + /// The number of files. + public int CountFiles(string parentDirectory = null) { using var conn = GetConnection(); @@ -256,14 +266,14 @@ namespace slskd.Shares try { - if (string.IsNullOrEmpty(prefix)) + if (string.IsNullOrEmpty(parentDirectory)) { cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn); } else { cmd = new SqliteCommand("SELECT COUNT(*) FROM files WHERE maskedFilename LIKE @prefix || '%'", conn); - cmd.Parameters.AddWithValue("prefix", prefix); + cmd.Parameters.AddWithValue("prefix", parentDirectory); } var reader = cmd.ExecuteReader(); @@ -276,6 +286,63 @@ namespace slskd.Shares } } + /// + /// Creates a new database. + /// + /// + /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case + /// tables are explicitly dropped prior to creation. + /// + /// An optional value that determines whether the existing database should be discarded. + public void Create(bool discardExisting = false) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("PRAGMA journal_mode=WAL"); + + if (discardExisting) + { + conn.ExecuteNonQuery("DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;"); + } + + conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL);"); + + conn.ExecuteNonQuery("CREATE VIRTUAL TABLE IF NOT EXISTS filenames USING fts5(maskedFilename);"); + + conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS 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, timestamp INTEGER NOT NULL);"); + } + + /// + /// Finds the filename of the file matching the specified . + /// + /// The fully qualified remote path of the file. + /// The filename, if found. + public string FindFilename (string maskedFilename) + { + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn); + cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); + + var reader = cmd.ExecuteReader(); + + if (!reader.Read()) + { + Log.Warning("Failed to resolve shared file {Filename}", maskedFilename); + return null; + } + + var resolved = reader.GetString(0); + Log.Debug($"Resolved requested shared file {maskedFilename} to {resolved}"); + return resolved; + } + + /// + /// Inserts a directory. + /// + /// The fully qualified local name of the directory. + /// The timestamp to assign to the record. public void InsertDirectory(string name, long timestamp) { using var conn = GetConnection(); @@ -287,6 +354,14 @@ namespace slskd.Shares }); } + /// + /// Inserts a file. + /// + /// The fully qualified remote path of the file. + /// The fully qualified local path of the file. + /// The timestamp at which the file was last modified, according to the host OS. + /// The Soulseek.File instance representing the file. + /// The timestamp to assign to the record. public void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, Soulseek.File file, long timestamp) { using var conn = GetConnection(); @@ -312,33 +387,12 @@ namespace slskd.Shares }); } - public long DeleteDirectories(long olderThanTimestamp) - { - using var conn = GetConnection(); - - using var cmd = new SqliteCommand("DELETE FROM directories WHERE timestamp < @timestamp; SELECT changes()", conn); - cmd.Parameters.AddWithValue("timestamp", olderThanTimestamp); - - var reader = cmd.ExecuteReader(); - reader.Read(); - - return reader.GetInt64(0); - } - - public long DeleteFiles(long olderThanTimestamp) - { - using var conn = GetConnection(); - - using var cmd = new SqliteCommand("DELETE FROM files WHERE timestamp < @timestamp; SELECT changes()", conn); - cmd.Parameters.AddWithValue("timestamp", olderThanTimestamp); - - var reader = cmd.ExecuteReader(); - reader.Read(); - - return reader.GetInt64(0); - } - - public IEnumerable ListDirectories(string prefix = null) + /// + /// Lists all directories. + /// + /// The optional directory prefix used for listing subdirectories. + /// The list of directories. + public IEnumerable ListDirectories(string parentDirectory = null) { var results = new List(); @@ -348,14 +402,14 @@ namespace slskd.Shares try { - if (string.IsNullOrEmpty(prefix)) + if (string.IsNullOrEmpty(parentDirectory)) { cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); } else { cmd = new SqliteCommand("SELECT name from directories WHERE name LIKE @prefix || '%' ORDER BY name ASC;", conn); - cmd.Parameters.AddWithValue("prefix", prefix); + cmd.Parameters.AddWithValue("prefix", parentDirectory); } var reader = cmd.ExecuteReader(); @@ -373,7 +427,13 @@ namespace slskd.Shares } } - public IEnumerable ListFiles(string directory = null, bool includeFullPath = false) + /// + /// Lists all files. + /// + /// The optional parent directory. + /// A value indicating whether the fully qualified path should be returned. + /// The list of files. + public IEnumerable ListFiles(string parentDirectory = null, bool includeFullPath = false) { var results = new List(); @@ -382,14 +442,14 @@ namespace slskd.Shares try { - if (string.IsNullOrEmpty(directory)) + if (string.IsNullOrEmpty(parentDirectory)) { cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); } else { cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ORDER BY maskedFilename ASC;", conn); - cmd.Parameters.AddWithValue("match", directory + '%'); + cmd.Parameters.AddWithValue("match", parentDirectory + '%'); } var reader = cmd.ExecuteReader(); @@ -418,5 +478,114 @@ namespace slskd.Shares cmd?.Dispose(); } } + + /// + /// Deletes directory records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete directories. + /// The number of records deleted. + public long PruneDirectories(long olderThanTimestamp) + { + using var conn = GetConnection(); + + using var cmd = new SqliteCommand("DELETE FROM directories WHERE timestamp < @timestamp; SELECT changes()", conn); + cmd.Parameters.AddWithValue("timestamp", olderThanTimestamp); + + var reader = cmd.ExecuteReader(); + reader.Read(); + + return reader.GetInt64(0); + } + + /// + /// Deletes file records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete files. + /// The number of records deleted. + public long PruneFiles(long olderThanTimestamp) + { + using var conn = GetConnection(); + + using var cmd = new SqliteCommand("DELETE FROM files WHERE timestamp < @timestamp; SELECT changes()", conn); + cmd.Parameters.AddWithValue("timestamp", olderThanTimestamp); + + var reader = cmd.ExecuteReader(); + reader.Read(); + + return reader.GetInt64(0); + } + + /// + /// Restores the current database from the database at the specified . + /// + /// The connection string of the source database. + public void RestoreFrom(string connectionString) + { + using var sourceConn = GetConnection(connectionString); + using var restoreConn = GetConnection(); + sourceConn.BackupDatabase(restoreConn); + } + + /// + /// Searches the database for files matching the specified . + /// + /// The search query. + /// The list of matching files. + public IEnumerable Search(SearchQuery query) + { + string Clean(string str) => str.Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " ") + .Replace("'", "''"); + + var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); + var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); + + var sql = $"SELECT files.maskedFilename, files.code, files.size, files.extension, files.attributeJson FROM filenames " + + "INNER JOIN files ON filenames.maskedFilename = files.maskedFilename " + + $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}' " + + "ORDER BY filenames.maskedFilename ASC;"; + + var results = new List(); + SqliteDataReader reader = default; + + try + { + using var conn = GetConnection(); + using var cmd = new SqliteCommand(sql, conn); + reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + var filename = reader.GetString(0); + var code = reader.GetInt32(1); + var size = reader.GetInt64(2); + var extension = reader.GetString(3); + var attributeJson = reader.GetString(4); + + var attributeList = attributeJson.FromJson>(); + + var file = new Soulseek.File(code, filename, size, extension, attributeList); + results.Add(file); + } + + return results; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); + return Enumerable.Empty(); + } + } + + private SqliteConnection GetConnection(string connectionString = null) + { + connectionString ??= ConnectionString; + + var conn = new SqliteConnection(connectionString); + conn.Open(); + return conn; + } } -} +} \ No newline at end of file diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 03b9cae5..08a4a425 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -123,10 +123,10 @@ namespace slskd.Shares // it's possible that the database was tampered with between the time it was checked at startup and now // validate the tables, and if there's an issue, drop and recreate everything. - if (!Repository.TryValidateTables(Program.ConnectionStrings.Shares)) + if (!ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares)) { Log.Warning("Shared file cache invalid; dropping and re-creating prior to scan."); - Repository.CreateTables(discardExisting: true); + Repository.Create(discardExisting: true); Log.Information("Share file cache ready."); } @@ -301,8 +301,8 @@ namespace slskd.Shares Log.Information("Scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; - var deletedFiles = Repository.DeleteFiles(timestamp); - var deletedDirectories = Repository.DeleteDirectories(timestamp); + var deletedFiles = Repository.PruneFiles(olderThanTimestamp: timestamp); + var deletedDirectories = Repository.PruneDirectories(olderThanTimestamp: timestamp); Log.Information("Removed or renamed {Files} files and {Directories} directories in {Elapsed}ms", deletedFiles, deletedDirectories, sw.ElapsedMilliseconds - swSnapshot); } @@ -315,7 +315,7 @@ namespace slskd.Shares } Log.Debug("Backing up shared file cache database..."); - Repository.Backup(Program.ConnectionStrings.SharesBackup); + Repository.BackupTo(Program.ConnectionStrings.SharesBackup); Log.Debug("Shared file cache database backup complete"); var directoryCount = Repository.CountDirectories(); diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index e11e59e9..ff40481e 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -174,7 +174,7 @@ namespace slskd.Shares /// public Task ResolveFileAsync(string remoteFilename) { - var resolvedFilename = Repository.FindOriginalFilename(remoteFilename.LocalizePath()); + var resolvedFilename = Repository.FindFilename(remoteFilename.LocalizePath()); if (string.IsNullOrEmpty(resolvedFilename)) { @@ -252,12 +252,12 @@ namespace slskd.Shares try { // see if we need to 'restore' the database from disk, and do so - if (CacheStorageMode == StorageMode.Memory || (CacheStorageMode == StorageMode.Disk && !Repository.TryValidateTables(Program.ConnectionStrings.Shares))) + if (CacheStorageMode == StorageMode.Memory || (CacheStorageMode == StorageMode.Disk && !ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares))) { Log.Debug($"Share cache {(CacheStorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup..."); // the backup is missing; we can't do anything but recreate it from scratch - if (!Repository.TryValidateTables(Program.ConnectionStrings.SharesBackup)) + if (!ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) { Log.Debug("Share cache backup is missing; unable to restore"); return false; @@ -265,7 +265,7 @@ namespace slskd.Shares Log.Debug("Share cache backup located. Attempting to restore..."); - Repository.Restore(sourceConnectionString: Program.ConnectionStrings.SharesBackup); + Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup); Log.Debug("Share cache successfully restored from backup"); } -- cgit v1.2.3