From 2989def8f55ef54571ea19635f6613c3358e3650 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Sep 2022 09:16:15 -0500 Subject: split most of the db logic into ShareRepository --- src/slskd/Shares/ShareRepository.cs | 339 ++++++++++++++++++++++++++++++++++++ 1 file changed, 339 insertions(+) create mode 100644 src/slskd/Shares/ShareRepository.cs (limited to 'src/slskd/Shares/ShareRepository.cs') diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs new file mode 100644 index 00000000..cdb6b12c --- /dev/null +++ b/src/slskd/Shares/ShareRepository.cs @@ -0,0 +1,339 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System; + using System.Collections.Generic; + using System.IO; + using Microsoft.Data.Sqlite; + using Serilog; + using Soulseek; + + 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 backupConnectionString); + } + + public class ShareRepository : IShareRepository + { + public ShareRepository(string connectionString) + { + ConnectionString = connectionString; + } + + private string ConnectionString { get; } + + private SqliteConnection GetConnection(string connectionString = null) + { + connectionString ??= ConnectionString; + + var conn = new SqliteConnection(connectionString); + conn.Open(); + return conn; + } + + public void CreateTables(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);"); + } + + public bool TryValidateTables(string connectionString) + { + var schema = new Dictionary() + { + { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, + { "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, timestamp INTEGER 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; + } + } + + public void Backup(string backupConnectionString) + { + using var sourceConn = GetConnection(ConnectionString); + using var backupConn = GetConnection(backupConnectionString); + sourceConn.BackupDatabase(backupConn); + } + + public int CountDirectories(string prefix = null) + { + using var conn = GetConnection(); + + SqliteCommand cmd = default; + + try + { + if (string.IsNullOrEmpty(prefix)) + { + 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); + } + + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + finally + { + cmd.Dispose(); + } + } + + public int CountFiles(string prefix = null) + { + using var conn = GetConnection(); + + SqliteCommand cmd = default; + + try + { + if (string.IsNullOrEmpty(prefix)) + { + 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); + } + + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + finally + { + cmd.Dispose(); + } + } + + public void InsertDirectory(string name, long timestamp) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("INSERT INTO directories VALUES(@name, @timestamp) ON CONFLICT DO UPDATE SET timestamp = excluded.timestamp;", cmd => + { + cmd.Parameters.AddWithValue("name", name); + cmd.Parameters.AddWithValue("timestamp", timestamp); + }); + } + + public void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, Soulseek.File file, long timestamp) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson, timestamp) " + + "VALUES(@maskedFilename, @originalFilename, @size, @touchedAt, @code, @extension, @attributeJson, @timestamp) " + + "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, size = excluded.size, touchedAt = excluded.touchedAt, " + + "code = excluded.code, extension = excluded.extension, attributeJson = excluded.attributeJson, timestamp = excluded.timestamp;", cmd => + { + cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); + cmd.Parameters.AddWithValue("originalFilename", originalFilename); + cmd.Parameters.AddWithValue("size", file.Size); + cmd.Parameters.AddWithValue("touchedAt", touchedAt.ToLongDateString()); + cmd.Parameters.AddWithValue("code", file.Code); + cmd.Parameters.AddWithValue("extension", file.Extension); + cmd.Parameters.AddWithValue("attributeJson", file.Attributes.ToJson()); + cmd.Parameters.AddWithValue("timestamp", timestamp); + }); + + conn.ExecuteNonQuery("INSERT INTO filenames (maskedFilename) VALUES(@maskedFilename);", cmd => + { + cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); + }); + } + + 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) + { + var results = new List(); + + using var conn = GetConnection(); + + SqliteCommand cmd = default; + + try + { + if (string.IsNullOrEmpty(prefix)) + { + 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); + } + + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results; + } + finally + { + cmd.Dispose(); + } + } + + public IEnumerable ListFiles(string directory = null, bool includeFullPath = false) + { + var results = new List(); + + SqliteCommand cmd = default; + using var conn = GetConnection(); + + try + { + if (string.IsNullOrEmpty(directory)) + { + 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 + '%'); + } + + var 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>(); + + filename = includeFullPath ? filename : Path.GetFileName(filename); + + var file = new Soulseek.File(code, filename, size, extension, attributeList); + + results.Add(file); + } + + return results; + } + finally + { + cmd?.Dispose(); + } + } + } +} -- cgit v1.2.3 From 77d1463b7183aa658cc7da3610b795d462ab493f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 27 Sep 2022 09:44:22 -0500 Subject: refactor resolve function --- src/slskd/Shares/ShareRepository.cs | 20 ++++++++++++++++++++ src/slskd/Shares/ShareService.cs | 2 +- src/slskd/Shares/SharedFileCache.cs | 33 --------------------------------- 3 files changed, 21 insertions(+), 34 deletions(-) (limited to 'src/slskd/Shares/ShareRepository.cs') diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs index cdb6b12c..dbfdd935 100644 --- a/src/slskd/Shares/ShareRepository.cs +++ b/src/slskd/Shares/ShareRepository.cs @@ -37,6 +37,7 @@ namespace slskd.Shares IEnumerable ListDirectories(string prefix = null); IEnumerable ListFiles(string directory = null, bool includeFullPath = false); void Backup(string backupConnectionString); + string FindOriginalFilename(string maskedFilename); } public class ShareRepository : IShareRepository @@ -57,6 +58,25 @@ namespace slskd.Shares return conn; } + public string FindOriginalFilename(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; + } + public void CreateTables(bool discardExisting = false) { using var conn = GetConnection(); diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 4505ea3e..8d647e74 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -168,7 +168,7 @@ namespace slskd.Shares /// public Task ResolveFileAsync(string remoteFilename) { - var resolvedFilename = Cache.Resolve(remoteFilename.LocalizePath()); + var resolvedFilename = Repository.FindOriginalFilename(remoteFilename.LocalizePath()); if (string.IsNullOrEmpty(resolvedFilename)) { diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 6e6cc6e6..6ccea3fc 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -50,14 +50,6 @@ namespace slskd.Shares /// The operation context. Task FillAsync(IEnumerable shares, IEnumerable filters); - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - string Resolve(string filename); - /// /// Searches the cache for the specified and returns the matching files. /// @@ -372,31 +364,6 @@ namespace slskd.Shares } } - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename) - { - using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn); - cmd.Parameters.AddWithValue("maskedFilename", filename); - - var reader = cmd.ExecuteReader(); - - if (!reader.Read()) - { - Log.Warning("Failed to resolve shared file {Filename}", filename); - return null; - } - - var resolved = reader.GetString(0); - Log.Debug($"Resolved requested shared file {filename} to {resolved}"); - return resolved; - } - /// /// Searches the cache for the specified and returns the matching files. /// -- cgit v1.2.3 From db7866c9b0cae53c53ba4d16f52a1653df646265 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Sep 2022 09:36:34 -0500 Subject: move search --- src/slskd/Shares/ShareRepository.cs | 55 ++++++++++++++++++++ src/slskd/Shares/ShareService.cs | 2 +- src/slskd/Shares/SharedFileCache.cs | 61 ----------------------- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- src/slskd/Transfers/Downloads/IDownloadService.cs | 2 +- 5 files changed, 58 insertions(+), 64 deletions(-) (limited to 'src/slskd/Shares/ShareRepository.cs') diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs index dbfdd935..5df77e6c 100644 --- a/src/slskd/Shares/ShareRepository.cs +++ b/src/slskd/Shares/ShareRepository.cs @@ -20,6 +20,7 @@ namespace slskd.Shares using System; using System.Collections.Generic; using System.IO; + using System.Linq; using Microsoft.Data.Sqlite; using Serilog; using Soulseek; @@ -38,6 +39,7 @@ namespace slskd.Shares IEnumerable ListFiles(string directory = null, bool includeFullPath = false); void Backup(string backupConnectionString); string FindOriginalFilename(string maskedFilename); + IEnumerable Search(SearchQuery query); } public class ShareRepository : IShareRepository @@ -58,6 +60,59 @@ namespace slskd.Shares return conn; } + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The 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(); + } + } + public string FindOriginalFilename(string maskedFilename) { using var conn = GetConnection(); diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 8d647e74..a0acdda1 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -194,7 +194,7 @@ namespace slskd.Shares /// The matching files. public Task> SearchAsync(SearchQuery query) { - var results = Cache.Search(query); + var results = Repository.Search(query); return Task.FromResult(results.Select(r => new File( r.Code, diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 6ccea3fc..4a443468 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -30,7 +30,6 @@ namespace slskd.Shares using System.Threading.Tasks; using Microsoft.Data.Sqlite; using Serilog; - using Soulseek; /// /// Shared file cache. @@ -50,13 +49,6 @@ namespace slskd.Shares /// The operation context. Task FillAsync(IEnumerable shares, IEnumerable filters); - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - IEnumerable Search(SearchQuery query); - /// /// Cancels the currently running fill operation, if one is running. /// @@ -364,59 +356,6 @@ namespace slskd.Shares } } - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The 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 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(); - } - } - /// /// Cancels the currently running fill operation, if one is running. /// diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 467ab4b3..9b4d14fc 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -59,7 +59,7 @@ namespace slskd.Transfers.Downloads /// /// Adds the specified . Supersedes any existing record for the same file and username. /// - /// This should generally not be called; use instead. + /// This should generally not be called; use EnqueueAsync() instead. /// public void AddOrSupersede(Transfer transfer) { diff --git a/src/slskd/Transfers/Downloads/IDownloadService.cs b/src/slskd/Transfers/Downloads/IDownloadService.cs index cc0064fd..b49d575c 100644 --- a/src/slskd/Transfers/Downloads/IDownloadService.cs +++ b/src/slskd/Transfers/Downloads/IDownloadService.cs @@ -30,7 +30,7 @@ namespace slskd.Transfers.Downloads /// /// Adds the specified . Supersedes any existing record for the same file and username. /// - /// This should generally not be called; use instead. + /// This should generally not be called; use EnqueueAsync() instead. /// void AddOrSupersede(Transfer transfer); -- cgit v1.2.3 From 1d4a478aa2b52a042592bca506b629ca249f9f63 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 28 Sep 2022 10:21:44 -0500 Subject: refactor sqlite backup --- src/slskd/Common/Sqlite.cs | 46 ++++++++++++++++++++++++++ src/slskd/Common/SqliteConnectionExtensions.cs | 32 ------------------ src/slskd/Shares/ShareRepository.cs | 6 ++-- src/slskd/Shares/SharedFileCache.cs | 13 ++------ 4 files changed, 52 insertions(+), 45 deletions(-) create mode 100644 src/slskd/Common/Sqlite.cs delete mode 100644 src/slskd/Common/SqliteConnectionExtensions.cs (limited to 'src/slskd/Shares/ShareRepository.cs') diff --git a/src/slskd/Common/Sqlite.cs b/src/slskd/Common/Sqlite.cs new file mode 100644 index 00000000..8f5784b6 --- /dev/null +++ b/src/slskd/Common/Sqlite.cs @@ -0,0 +1,46 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using Microsoft.Data.Sqlite; + + public static class Sqlite + { + public static void Backup(string sourceConnectionString, string destinationConnectionString) + { + using var source = new SqliteConnection(sourceConnectionString); + using var destination = new SqliteConnection(destinationConnectionString); + + source.Open(); + destination.Open(); + + source.BackupDatabase(destination); + } + + public static void Restore(string sourceConnectionString, string destinationConnectionString) + => Backup(sourceConnectionString, destinationConnectionString); + + public static int ExecuteNonQuery(this SqliteConnection conn, string query, Action action = null) + { + using var cmd = new SqliteCommand(query, conn); + action?.Invoke(cmd); + return cmd.ExecuteNonQuery(); + } + } +} diff --git a/src/slskd/Common/SqliteConnectionExtensions.cs b/src/slskd/Common/SqliteConnectionExtensions.cs deleted file mode 100644 index 3944c10b..00000000 --- a/src/slskd/Common/SqliteConnectionExtensions.cs +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using Microsoft.Data.Sqlite; - - public static class SqliteConnectionExtensions - { - public static int ExecuteNonQuery(this SqliteConnection conn, string query, Action action = null) - { - using var cmd = new SqliteCommand(query, conn); - action?.Invoke(cmd); - return cmd.ExecuteNonQuery(); - } - } -} diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs index 5df77e6c..a79e0f05 100644 --- a/src/slskd/Shares/ShareRepository.cs +++ b/src/slskd/Shares/ShareRepository.cs @@ -37,7 +37,7 @@ namespace slskd.Shares long DeleteFiles(long olderThanTimestamp); IEnumerable ListDirectories(string prefix = null); IEnumerable ListFiles(string directory = null, bool includeFullPath = false); - void Backup(string backupConnectionString); + void Backup(string destinationConnectionString); string FindOriginalFilename(string maskedFilename); IEnumerable Search(SearchQuery query); } @@ -205,10 +205,10 @@ namespace slskd.Shares } } - public void Backup(string backupConnectionString) + public void Backup(string destinationConnectionString) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(backupConnectionString); + using var backupConn = GetConnection(destinationConnectionString); sourceConn.BackupDatabase(backupConn); } diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 4a443468..93a7da59 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -393,9 +393,9 @@ namespace slskd.Shares Log.Debug("Share cache backup located. Attempting to restore..."); - using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup); - using var conn = GetConnection(); - backupConn.BackupDatabase(conn); + Sqlite.Restore( + sourceConnectionString: Program.ConnectionStrings.SharesBackup, + destinationConnectionString: Program.ConnectionStrings.Shares); Log.Debug("Share cache successfully restored from backup"); } @@ -423,12 +423,5 @@ namespace slskd.Shares return false; } } - - private SqliteConnection GetConnection(string connectionString = null) - { - var conn = new SqliteConnection(connectionString ?? Program.ConnectionStrings.Shares); - conn.Open(); - return conn; - } } } \ No newline at end of file -- cgit v1.2.3 From 0727a46658b6de94edcedbb1e496b08d2737ca31 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 29 Sep 2022 08:27:31 -0500 Subject: move backup and restore --- src/slskd/Common/Sqlite.cs | 14 -------------- src/slskd/Shares/ShareRepository.cs | 8 ++++++++ src/slskd/Shares/ShareService.cs | 4 +--- 3 files changed, 9 insertions(+), 17 deletions(-) (limited to 'src/slskd/Shares/ShareRepository.cs') diff --git a/src/slskd/Common/Sqlite.cs b/src/slskd/Common/Sqlite.cs index 8f5784b6..14460da1 100644 --- a/src/slskd/Common/Sqlite.cs +++ b/src/slskd/Common/Sqlite.cs @@ -22,20 +22,6 @@ namespace slskd public static class Sqlite { - public static void Backup(string sourceConnectionString, string destinationConnectionString) - { - using var source = new SqliteConnection(sourceConnectionString); - using var destination = new SqliteConnection(destinationConnectionString); - - source.Open(); - destination.Open(); - - source.BackupDatabase(destination); - } - - public static void Restore(string sourceConnectionString, string destinationConnectionString) - => Backup(sourceConnectionString, destinationConnectionString); - public static int ExecuteNonQuery(this SqliteConnection conn, string query, Action action = null) { using var cmd = new SqliteCommand(query, conn); diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs index a79e0f05..c01c9d83 100644 --- a/src/slskd/Shares/ShareRepository.cs +++ b/src/slskd/Shares/ShareRepository.cs @@ -38,6 +38,7 @@ namespace slskd.Shares 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); } @@ -212,6 +213,13 @@ namespace slskd.Shares 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) { using var conn = GetConnection(); diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index d5fd417e..e11e59e9 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -265,9 +265,7 @@ namespace slskd.Shares Log.Debug("Share cache backup located. Attempting to restore..."); - Sqlite.Restore( - sourceConnectionString: Program.ConnectionStrings.SharesBackup, - destinationConnectionString: Program.ConnectionStrings.Shares); + Repository.Restore(sourceConnectionString: Program.ConnectionStrings.SharesBackup); Log.Debug("Share cache successfully restored from backup"); } -- cgit v1.2.3 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/slskd/Shares/ShareRepository.cs') 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 From 65bb516bd6d9d8caa262d5e3d1369f4221ab38dd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 1 Oct 2022 17:24:34 -0500 Subject: use correct logger --- src/slskd/Program.cs | 6 ++++-- src/slskd/Shares/ShareRepository.cs | 10 +++++++--- src/slskd/Shares/ShareScanner.cs | 6 +++--- src/slskd/Shares/ShareService.cs | 16 ++++++++++++---- 4 files changed, 26 insertions(+), 12 deletions(-) (limited to 'src/slskd/Shares/ShareRepository.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 03870f0a..8dbf39ff 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -823,9 +823,11 @@ namespace slskd outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .WriteTo.Sink(new DelegatingSink(logEvent => { + string message = default; + try { - var message = logEvent.RenderMessage(); + message = logEvent.RenderMessage(); if (logEvent.Exception != null) { @@ -846,7 +848,7 @@ namespace slskd } catch (Exception ex) { - Log.Information($"Misconfigured delegating logger: {ex.Message}"); + Log.Error("Misconfigured delegating logger: {Exception}. Message: {Message}", ex.Message, message); } })) .CreateLogger(); diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs index ba4b714c..b8ecd2be 100644 --- a/src/slskd/Shares/ShareRepository.cs +++ b/src/slskd/Shares/ShareRepository.cs @@ -23,6 +23,7 @@ namespace slskd.Shares using System.Linq; using Microsoft.Data.Sqlite; using Serilog; + using slskd.Transfers.Uploads; using Soulseek; /// @@ -142,6 +143,7 @@ namespace slskd.Shares } private string ConnectionString { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Attempts to validate the database at the specified . @@ -156,6 +158,8 @@ namespace slskd.Shares throw new ArgumentNullException(nameof(connectionString), "A connection string is required"); } + var log = Serilog.Log.ForContext(); + var schema = new Dictionary() { { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, @@ -165,7 +169,7 @@ namespace slskd.Shares try { - Log.Debug("Validating shares database with connection string {String}", connectionString); + log.Debug("Validating shares database with connection string {String}", connectionString); using var conn = new SqliteConnection(connectionString); conn.Open(); @@ -188,7 +192,7 @@ namespace slskd.Shares } else { - Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); + log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); } } @@ -204,7 +208,7 @@ namespace slskd.Shares } catch (Exception ex) { - Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); + log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); return false; } } diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 3edd84c1..369e4981 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -125,12 +125,12 @@ namespace slskd.Shares // validate the tables, and if there's an issue, drop and recreate everything. if (!ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares)) { - Log.Warning("Shared file cache invalid; dropping and re-creating prior to scan."); + Log.Warning("Shared file cache missing or invalid. Re-creating prior to scan."); Repository.Create(discardExisting: true); - Log.Information("Share file cache ready."); + Log.Information("Shared file cache re-created and ready for scan."); } - Log.Debug("Starting shared file scan"); + Log.Information("Starting shared file scan"); var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index cebb15f6..4c107ed2 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -28,6 +28,7 @@ namespace slskd.Shares using System.Threading; using System.Threading.Tasks; using Serilog; + using slskd.Transfers.Uploads; using Soulseek; /// @@ -96,6 +97,7 @@ namespace slskd.Shares private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private List FilterRegexes { get; set; } = new List(); private StorageMode CacheStorageMode { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Returns the entire contents of the share. @@ -267,12 +269,18 @@ namespace slskd.Shares Log.Warning("Share cache couldn't be loaded from backup"); await InitializeAsync(forceRescan: true); } + else + { + Log.Debug("Share cache backup located. Attempting to restore..."); - Log.Debug("Share cache backup located. Attempting to restore..."); - - Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup); + Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup); - Log.Information("Share cache successfully restored from backup"); + Log.Information("Share cache successfully restored from backup"); + } + } + else + { + // the cache mode is disk and the existing db is valid. nothing to do. } // one of several thigns happened above before we got here: -- cgit v1.2.3