From da88bbb819dfa4420c97c09a840748942bc7f081 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 11 Oct 2022 18:59:35 -0500 Subject: separate read/write interfaces --- src/slskd/Shares/ShareRepository.cs | 85 ++++++++++++++++++++++--------------- 1 file changed, 50 insertions(+), 35 deletions(-) diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs index 7b723ac6..fd69c2a3 100644 --- a/src/slskd/Shares/ShareRepository.cs +++ b/src/slskd/Shares/ShareRepository.cs @@ -26,15 +26,14 @@ namespace slskd.Shares using Soulseek; /// - /// Persistent storage of shared files and metadata. + /// Read-only persistent storage of shared files and metadata. /// - public interface IShareRepository + public interface IReadOnlyShareRepository { /// - /// Backs the current database up to the database at the specified . + /// Gets the connection string for this repository. /// - /// The connection string of the destination database. - void BackupTo(string connectionString); + string ConnectionString { get; } /// /// Counts the number of directories in the database. @@ -50,6 +49,41 @@ namespace slskd.Shares /// The number of files. int CountFiles(string parentDirectory = null); + /// + /// Finds the filename of the file matching the specified . + /// + /// The fully qualified remote path of the file. + /// The filename, if found. + string FindFilename(string maskedFilename); + + /// + /// Lists all directories. + /// + /// The optional directory prefix used for listing subdirectories. + /// The list of directories. + IEnumerable ListDirectories(string parentDirectory = null); + + /// + /// 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); + + /// + /// Searches the database for files matching the specified . + /// + /// The search query. + /// The list of matching files. + IEnumerable Search(SearchQuery query); + } + + /// + /// Writeable persistent storage of shared files and metadata. + /// + public interface IShareRepository : IReadOnlyShareRepository + { /// /// Creates a new database. /// @@ -60,13 +94,6 @@ namespace slskd.Shares /// An optional value that determines whether the existing database should be discarded. void Create(bool discardExisting = false); - /// - /// Finds the filename of the file matching the specified . - /// - /// The fully qualified remote path of the file. - /// The filename, if found. - string FindFilename(string maskedFilename); - /// /// Inserts a directory. /// @@ -92,19 +119,16 @@ namespace slskd.Shares void InsertScan(long timestamp, Options.SharesOptions options); /// - /// Lists all directories. + /// Backs the current database up to the database at the specified . /// - /// The optional directory prefix used for listing subdirectories. - /// The list of directories. - IEnumerable ListDirectories(string parentDirectory = null); + /// The connection string of the destination database. + void BackupTo(string connectionString); /// - /// Lists all files. + /// Restores the current database from the database at the specified . /// - /// 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); + /// The connection string of the source database. + void RestoreFrom(string connectionString); /// /// Deletes directory records with a timestamp prior to the specified . @@ -120,19 +144,6 @@ namespace slskd.Shares /// The number of records deleted. long PruneFiles(long olderThanTimestamp); - /// - /// Restores the current database from the database at the specified . - /// - /// The connection string of the source database. - void RestoreFrom(string connectionString); - - /// - /// Searches the database for files matching the specified . - /// - /// The search query. - /// The list of matching files. - IEnumerable Search(SearchQuery query); - /// /// Updates the scan started at the specified to set the . /// @@ -155,7 +166,11 @@ namespace slskd.Shares ConnectionString = connectionString; } - private string ConnectionString { get; } + /// + /// Gets the connection string for this repository. + /// + public string ConnectionString { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); /// -- cgit v1.2.3 From 56f164196192ffbe62bb9ba2684d5db45f223f24 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 11 Oct 2022 19:05:55 -0500 Subject: add agent shares --- src/slskd/Shares/IShareService.cs | 12 ++++++++++++ src/slskd/Shares/ShareService.cs | 28 +++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 2a18f5b3..3ec5fd56 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -38,6 +38,18 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor { get; } + /// + /// Adds the shares associated with the specified . + /// + /// The name of the agent. + void AddAgentShares(string agent); + + /// + /// Remotes the shares associated with the specified . + /// + /// The name of the agent. + void RemoveAgentShares(string agent); + /// /// Returns the entire contents of the share. /// diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index a9c8c629..d500532d 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -24,7 +24,6 @@ namespace slskd.Shares using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; - using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Serilog; @@ -96,6 +95,33 @@ namespace slskd.Shares private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private ConcurrentDictionary AgentRepositories { get; } = new(); + + /// + /// Adds the shares associated with the specified . + /// + /// The name of the agent. + public void AddAgentShares(string agent) + { + if (string.IsNullOrEmpty(agent)) + { + throw new ArgumentNullException(nameof(agent)); + } + + AgentRepositories.AddOrUpdate( + key: agent, + addValue: new ShareRepository(BuildConnectionString(agent)), + updateValueFactory: (agent, repository) => new ShareRepository(BuildConnectionString(agent))); + } + + /// + /// Remotes the shares associated with the specified . + /// + /// The name of the agent. + public void RemoveAgentShares(string agent) + { + AgentRepositories.TryRemove(agent, out _); + } /// /// Returns the entire contents of the share. -- cgit v1.2.3 From 3fa4868b6eea332327ece82a9b7d34ea0be65acc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 11 Oct 2022 19:06:10 -0500 Subject: add connection string factory --- src/slskd/Shares/ShareService.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index d500532d..24164690 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -365,6 +365,7 @@ namespace slskd.Shares } } + private string BuildConnectionString(string agent = null) => $"Data Source={agent}{(!string.IsNullOrEmpty(agent) ? "." : string.Empty)}shares.db"; private void Configure(Options options) { SyncRoot.Wait(); -- cgit v1.2.3 From 6a16de6dab8759051ad36bf788da634277bdede2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 11 Oct 2022 19:06:27 -0500 Subject: spacing --- src/slskd/Shares/ShareService.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 24164690..9ab96da9 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -366,6 +366,7 @@ namespace slskd.Shares } private string BuildConnectionString(string agent = null) => $"Data Source={agent}{(!string.IsNullOrEmpty(agent) ? "." : string.Empty)}shares.db"; + private void Configure(Options options) { SyncRoot.Wait(); -- cgit v1.2.3 From 780e9b5fd515421a12cea3b35308889f70370e6e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Oct 2022 08:19:09 -0500 Subject: split interfaces from repository implementation, rename repository to sqlite specific --- src/slskd/Shares/IReadOnlyShareRepository.cs | 76 +++ src/slskd/Shares/IShareRepository.cs | 95 ++++ src/slskd/Shares/ShareRepository.cs | 665 --------------------------- src/slskd/Shares/ShareService.cs | 12 +- src/slskd/Shares/SqliteShareRepository.cs | 537 +++++++++++++++++++++ 5 files changed, 714 insertions(+), 671 deletions(-) create mode 100644 src/slskd/Shares/IReadOnlyShareRepository.cs create mode 100644 src/slskd/Shares/IShareRepository.cs delete mode 100644 src/slskd/Shares/ShareRepository.cs create mode 100644 src/slskd/Shares/SqliteShareRepository.cs diff --git a/src/slskd/Shares/IReadOnlyShareRepository.cs b/src/slskd/Shares/IReadOnlyShareRepository.cs new file mode 100644 index 00000000..ae2e4c6a --- /dev/null +++ b/src/slskd/Shares/IReadOnlyShareRepository.cs @@ -0,0 +1,76 @@ +// +// 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.Collections.Generic; + using Soulseek; + + /// + /// Read-only persistent storage of shared files and metadata. + /// + public interface IReadOnlyShareRepository + { + /// + /// Gets the connection string for this repository. + /// + 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); + + /// + /// 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); + + /// + /// Finds the filename of the file matching the specified . + /// + /// The fully qualified remote path of the file. + /// The filename, if found. + string FindFilename(string maskedFilename); + + /// + /// Lists all directories. + /// + /// The optional directory prefix used for listing subdirectories. + /// The list of directories. + IEnumerable ListDirectories(string parentDirectory = null); + + /// + /// 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); + + /// + /// Searches the database for files matching the specified . + /// + /// The search query. + /// The list of matching files. + IEnumerable Search(SearchQuery query); + } +} diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs new file mode 100644 index 00000000..59c9537e --- /dev/null +++ b/src/slskd/Shares/IShareRepository.cs @@ -0,0 +1,95 @@ +// +// 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 Soulseek; + + /// + /// Writeable persistent storage of shared files and metadata. + /// + public interface IShareRepository : IReadOnlyShareRepository + { + /// + /// 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); + + /// + /// Inserts a directory. + /// + /// The fully qualified local name of the directory. + /// The timestamp to assign to the record. + void InsertDirectory(string name, long timestamp); + + /// + /// 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, File file, long timestamp); + + /// + /// Inserts a scan record at the specified . + /// + /// The timestamp associated with the scan. + /// The options snapshot at the start of the scan. + void InsertScan(long timestamp, Options.SharesOptions options); + + /// + /// Backs the current database up to the database at the specified . + /// + /// The connection string of the destination database. + void BackupTo(string connectionString); + + /// + /// Restores the current database from the database at the specified . + /// + /// The connection string of the source database. + void RestoreFrom(string connectionString); + + /// + /// 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); + + /// + /// 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); + + /// + /// Updates the scan started at the specified to set the . + /// + /// The timestamp associated with the scan. + /// The timestamp at the conclusion of the scan. + void UpdateScan(long timestamp, long end); + } +} \ No newline at end of file diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs deleted file mode 100644 index fd69c2a3..00000000 --- a/src/slskd/Shares/ShareRepository.cs +++ /dev/null @@ -1,665 +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.Shares -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using Microsoft.Data.Sqlite; - using Serilog; - using Soulseek; - - /// - /// Read-only persistent storage of shared files and metadata. - /// - public interface IReadOnlyShareRepository - { - /// - /// Gets the connection string for this repository. - /// - 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); - - /// - /// 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); - - /// - /// Finds the filename of the file matching the specified . - /// - /// The fully qualified remote path of the file. - /// The filename, if found. - string FindFilename(string maskedFilename); - - /// - /// Lists all directories. - /// - /// The optional directory prefix used for listing subdirectories. - /// The list of directories. - IEnumerable ListDirectories(string parentDirectory = null); - - /// - /// 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); - - /// - /// Searches the database for files matching the specified . - /// - /// The search query. - /// The list of matching files. - IEnumerable Search(SearchQuery query); - } - - /// - /// Writeable persistent storage of shared files and metadata. - /// - public interface IShareRepository : IReadOnlyShareRepository - { - /// - /// 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); - - /// - /// Inserts a directory. - /// - /// The fully qualified local name of the directory. - /// The timestamp to assign to the record. - void InsertDirectory(string name, long timestamp); - - /// - /// 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); - - /// - /// Inserts a scan record at the specified . - /// - /// The timestamp associated with the scan. - /// The options snapshot at the start of the scan. - void InsertScan(long timestamp, Options.SharesOptions options); - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - void BackupTo(string connectionString); - - /// - /// Restores the current database from the database at the specified . - /// - /// The connection string of the source database. - void RestoreFrom(string connectionString); - - /// - /// 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); - - /// - /// 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); - - /// - /// Updates the scan started at the specified to set the . - /// - /// The timestamp associated with the scan. - /// The timestamp at the conclusion of the scan. - void UpdateScan(long timestamp, long end); - } - - /// - /// Persistent storage of shared files and metadata. - /// - public class ShareRepository : IShareRepository - { - /// - /// Initializes a new instance of the class. - /// - /// - public ShareRepository(string connectionString) - { - ConnectionString = connectionString; - } - - /// - /// Gets the connection string for this repository. - /// - public string ConnectionString { get; } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// 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) - { - throw new ArgumentNullException(nameof(connectionString), "A connection string is required"); - } - - var log = Serilog.Log.ForContext(); - - // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: - // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' - var schema = new Dictionary() - { - { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, - { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, - { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, - { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, - { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, - { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, - { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, - { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, - { "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 = new SqliteConnection(connectionString); - conn.Open(); - - using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", 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; - } - } - - /// - /// 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(connectionString); - sourceConn.BackupDatabase(backupConn); - } - - /// - /// 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(); - - SqliteCommand cmd = default; - - try - { - 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", parentDirectory); - } - - var reader = cmd.ExecuteReader(); - reader.Read(); - return reader.GetInt32(0); - } - finally - { - cmd.Dispose(); - } - } - - /// - /// 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(); - - SqliteCommand cmd = default; - - try - { - 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", parentDirectory); - } - - var reader = cmd.ExecuteReader(); - reader.Read(); - return reader.GetInt32(0); - } - finally - { - cmd.Dispose(); - } - } - - /// - /// 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 scans; DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;"); - } - - conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL);"); - - 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(); - - 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); - }); - } - - /// - /// 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(); - - 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); - }); - } - - /// - /// Inserts a scan record at the specified . - /// - /// The timestamp associated with the scan. - /// The options snapshot at the start of the scan. - public void InsertScan(long timestamp, Options.SharesOptions options) - { - using var conn = GetConnection(); - - conn.ExecuteNonQuery("INSERT INTO scans (timestamp, options) VALUES(@timestamp, @options)", cmd => - { - cmd.Parameters.AddWithValue("timestamp", timestamp); - cmd.Parameters.AddWithValue("options", options.ToJson()); - }); - } - - /// - /// 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(); - - using var conn = GetConnection(); - - SqliteCommand cmd = default; - - try - { - 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", parentDirectory); - } - - var reader = cmd.ExecuteReader(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - - return results; - } - finally - { - cmd.Dispose(); - } - } - - /// - /// 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(); - - SqliteCommand cmd = default; - using var conn = GetConnection(); - - try - { - 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", parentDirectory + '%'); - } - - 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(); - } - } - - /// - /// 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(); - } - } - - /// - /// Updates the scan started at the specified to set the . - /// - /// The timestamp associated with the scan. - /// The timestamp at the conclusion of the scan. - public void UpdateScan(long timestamp, long end) - { - using var conn = GetConnection(); - - conn.ExecuteNonQuery("UPDATE scans SET end = @end WHERE timestamp = @timestamp;", cmd => - { - cmd.Parameters.AddWithValue("end", end); - cmd.Parameters.AddWithValue("timestamp", timestamp); - }); - } - - 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/ShareService.cs b/src/slskd/Shares/ShareService.cs index 9ab96da9..c88a2345 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -66,7 +66,7 @@ namespace slskd.Shares }); }); - Repository = new ShareRepository(connectionString: Program.ConnectionStrings.Shares); + Repository = new SqliteShareRepository(connectionString: Program.ConnectionStrings.Shares); OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); @@ -110,8 +110,8 @@ namespace slskd.Shares AgentRepositories.AddOrUpdate( key: agent, - addValue: new ShareRepository(BuildConnectionString(agent)), - updateValueFactory: (agent, repository) => new ShareRepository(BuildConnectionString(agent))); + addValue: new SqliteShareRepository(BuildConnectionString(agent)), + updateValueFactory: (_, repository) => new SqliteShareRepository(BuildConnectionString(agent))); } /// @@ -289,7 +289,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) + if (SqliteShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) { Log.Information("Share cache backup validated. Attempting to restore..."); @@ -307,7 +307,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares)) + if (SqliteShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares)) { // no-op } @@ -315,7 +315,7 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) + if (SqliteShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) { Log.Information("Share cache backup validated. Attempting to restore..."); diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs new file mode 100644 index 00000000..6a91ef82 --- /dev/null +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -0,0 +1,537 @@ +// +// 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 System.Linq; + using Microsoft.Data.Sqlite; + using Serilog; + using Soulseek; + + /// + /// Persistent storage of shared files and metadata. + /// + public class SqliteShareRepository : IShareRepository + { + /// + /// Initializes a new instance of the class. + /// + /// + public SqliteShareRepository(string connectionString) + { + ConnectionString = connectionString; + } + + /// + /// Gets the connection string for this repository. + /// + public string ConnectionString { get; } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// 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) + { + throw new ArgumentNullException(nameof(connectionString), "A connection string is required"); + } + + var log = Serilog.Log.ForContext(); + + // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: + // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' + var schema = new Dictionary() + { + { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, + { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, + { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, + { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, + { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, + { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, + { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, + { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, + { "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 = new SqliteConnection(connectionString); + conn.Open(); + + using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", 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; + } + } + + /// + /// 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(connectionString); + sourceConn.BackupDatabase(backupConn); + } + + /// + /// 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(); + + SqliteCommand cmd = default; + + try + { + 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", parentDirectory); + } + + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + finally + { + cmd?.Dispose(); + } + } + + /// + /// 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(); + + SqliteCommand cmd = default; + + try + { + 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", parentDirectory); + } + + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + finally + { + cmd?.Dispose(); + } + } + + /// + /// 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 scans; DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;"); + } + + conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL);"); + + 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(); + + 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); + }); + } + + /// + /// 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(); + + 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); + }); + } + + /// + /// Inserts a scan record at the specified . + /// + /// The timestamp associated with the scan. + /// The options snapshot at the start of the scan. + public void InsertScan(long timestamp, Options.SharesOptions options) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("INSERT INTO scans (timestamp, options) VALUES(@timestamp, @options)", cmd => + { + cmd.Parameters.AddWithValue("timestamp", timestamp); + cmd.Parameters.AddWithValue("options", options.ToJson()); + }); + } + + /// + /// 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(); + + using var conn = GetConnection(); + + SqliteCommand cmd = default; + + try + { + 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", parentDirectory); + } + + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results; + } + finally + { + cmd?.Dispose(); + } + } + + /// + /// 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(); + + SqliteCommand cmd = default; + using var conn = GetConnection(); + + try + { + 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", parentDirectory + '%'); + } + + 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(); + } + } + + /// + /// 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(); + + try + { + using var conn = GetConnection(); + using var cmd = new SqliteCommand(sql, conn); + using 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>(); + + 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(); + } + } + + /// + /// Updates the scan started at the specified to set the . + /// + /// The timestamp associated with the scan. + /// The timestamp at the conclusion of the scan. + public void UpdateScan(long timestamp, long end) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("UPDATE scans SET end = @end WHERE timestamp = @timestamp;", cmd => + { + cmd.Parameters.AddWithValue("end", end); + cmd.Parameters.AddWithValue("timestamp", timestamp); + }); + } + + private SqliteConnection GetConnection(string connectionString = null) + { + connectionString ??= ConnectionString; + + var conn = new SqliteConnection(connectionString); + conn.Open(); + return conn; + } + } +} \ No newline at end of file -- cgit v1.2.3 From 3872c9f3af689937f834434caa462ddc23cb9663 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Oct 2022 09:12:08 -0500 Subject: eliminate ConnectionStrings class --- src/slskd/Core/ConnectionStrings.cs | 30 ------------------------------ 1 file changed, 30 deletions(-) delete mode 100644 src/slskd/Core/ConnectionStrings.cs diff --git a/src/slskd/Core/ConnectionStrings.cs b/src/slskd/Core/ConnectionStrings.cs deleted file mode 100644 index 6afab93f..00000000 --- a/src/slskd/Core/ConnectionStrings.cs +++ /dev/null @@ -1,30 +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 -{ - /// - /// Application connection strings. - /// - public record ConnectionStrings - { - public string Transfers { get; init; } - public string Shares { get; init; } - public string SharesBackup { get; init; } - public string Search { get; init; } - } -} -- cgit v1.2.3 From e83e6e9f55a1b01ae311a5356ad6251fe8e8c0dc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Oct 2022 09:12:22 -0500 Subject: add ShareConnectionStringFactory --- src/slskd/Shares/ShareConnectionStringFactory.cs | 58 ++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/slskd/Shares/ShareConnectionStringFactory.cs diff --git a/src/slskd/Shares/ShareConnectionStringFactory.cs b/src/slskd/Shares/ShareConnectionStringFactory.cs new file mode 100644 index 00000000..d9b7492b --- /dev/null +++ b/src/slskd/Shares/ShareConnectionStringFactory.cs @@ -0,0 +1,58 @@ +// +// 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; + + /// + /// Creates connection strings for share cache databases. + /// + public class ShareConnectionStringFactory + { + /// + /// Initializes a new instance of the class. + /// + /// The function used to create a connection string for a share cache database. + /// The function used to create an in-memory connection string for a share cache database. + /// The function used to crate a connection string for a share cache backup database. + public ShareConnectionStringFactory( + Func createFromFile, + Func createFromMemory, + Func createBackupFromFile) + { + CreateFromFile = createFromFile; + CreateFromMemory = createFromMemory; + CreateBackupFromFile = createBackupFromFile; + } + + /// + /// Gets a function used to create a connection string for a share cache database. + /// + public Func CreateFromFile { get; } + + /// + /// Gets a function used to create an in-memory connection string for a share cache database. + /// + public Func CreateFromMemory { get; } + + /// + /// Gets a function used to create a connection string for a share cache backup database. + /// + public Func CreateBackupFromFile { get; } + } +} -- cgit v1.2.3 From ac54baf2b8472b39edf75d685049620c112c665c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Oct 2022 09:16:06 -0500 Subject: refactor connection string handling --- src/slskd/Program.cs | 21 ++++++--------------- src/slskd/Shares/ShareService.cs | 29 +++++++++++++++++++++++------ 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 8b816f48..c3e39c1d 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -161,11 +161,6 @@ namespace slskd [EnvironmentVariable("CONFIG")] public static string ConfigurationFile { get; private set; } = null; - /// - /// Gets the connection strings for application databases. - /// - public static ConnectionStrings ConnectionStrings { get; private set; } = null; - /// /// Gets the path where persistent data is saved. /// @@ -409,14 +404,6 @@ namespace slskd 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); @@ -536,14 +523,18 @@ namespace slskd services.AddSingleton(); - services.AddDbContext(ConnectionStrings.Search); - services.AddDbContext(ConnectionStrings.Transfers); + services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;"); + services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;"); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(); + services.AddSingleton(new ShareConnectionStringFactory( + createFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, name)}.db;Cache=shared", + createFromMemory: (name) => $"file:{name}?mode=memory", + createBackupFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, name)}.db.bak;")); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index d1b9aef1..b44b79ff 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -37,12 +37,15 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// + /// /// /// public ShareService( + ShareConnectionStringFactory shareConnectionStringFactory, IOptionsMonitor optionsMonitor, IShareScanner scanner = null) { + ConnectionStringFactory = shareConnectionStringFactory; CacheStorageMode = optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum(); Scanner = scanner ?? new ShareScanner( @@ -66,7 +69,18 @@ namespace slskd.Shares }); }); - Repository = new SqliteShareRepository(connectionString: Program.ConnectionStrings.Shares); + if (CacheStorageMode == StorageMode.Memory) + { + ConnectionString = ConnectionStringFactory.CreateFromMemory("shares"); + } + else + { + ConnectionString = ConnectionStringFactory.CreateFromFile("shares"); + } + + BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile("shares"); + + Repository = new SqliteShareRepository(ConnectionString); OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); @@ -86,6 +100,9 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor { get; } + private string ConnectionString { get; } + private string BackupConnectionString { get; } + private ShareConnectionStringFactory ConnectionStringFactory { get; } private IShareScanner Scanner { get; } private IShareRepository Repository { get; } private string LastOptionsHash { get; set; } @@ -289,11 +306,11 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (SqliteShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) + if (SqliteShareRepository.TryValidateDatabase(BackupConnectionString)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup); + Repository.RestoreFrom(connectionString: BackupConnectionString); Log.Information("Share cache successfully restored from backup"); } @@ -307,7 +324,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (SqliteShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares)) + if (SqliteShareRepository.TryValidateDatabase(ConnectionString)) { // no-op } @@ -315,11 +332,11 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (SqliteShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) + if (SqliteShareRepository.TryValidateDatabase(BackupConnectionString)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup); + Repository.RestoreFrom(connectionString: BackupConnectionString); Log.Information("Share cache successfully restored from backup"); } -- cgit v1.2.3 From 99ba8a9fbc4f809041df12d1ad6334733c714144 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Oct 2022 10:30:56 -0500 Subject: remove connection string leftover --- src/slskd/Program.cs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c3e39c1d..55957718 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -390,20 +390,6 @@ namespace slskd RecreateConfigurationFileIfMissing(ConfigurationFile); - // configure connection strings and configure SQLite - string shareDbDataSource = default; - - if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == 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"; - } - if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); -- cgit v1.2.3 From 460014a97bef714513564999d9955804d5ea715f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Oct 2022 18:31:19 -0500 Subject: make validation method instance --- src/slskd/Program.cs | 1 + src/slskd/Shares/IReadOnlyShareRepository.cs | 8 ++++++++ src/slskd/Shares/ShareScanner.cs | 13 ++++++------- src/slskd/Shares/ShareService.cs | 20 +++++++++++++------- src/slskd/Shares/SqliteShareRepository.cs | 19 +++++++------------ 5 files changed, 35 insertions(+), 26 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 55957718..44558e85 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -39,6 +39,7 @@ namespace slskd using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ApiExplorer; + using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; diff --git a/src/slskd/Shares/IReadOnlyShareRepository.cs b/src/slskd/Shares/IReadOnlyShareRepository.cs index ae2e4c6a..9822f536 100644 --- a/src/slskd/Shares/IReadOnlyShareRepository.cs +++ b/src/slskd/Shares/IReadOnlyShareRepository.cs @@ -72,5 +72,13 @@ namespace slskd.Shares /// The search query. /// The list of matching files. IEnumerable Search(SearchQuery query); + + /// + /// Attempts to validate the database at the specified , or the + /// default . + /// + /// The connection string of the database to validate. + /// A value indicating whether the database is valid. + bool TryValidate(string connectionString = null); } } diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 74f0d131..7a174396 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -65,11 +65,14 @@ namespace slskd.Shares /// /// /// - public ShareScanner(int workerCount, ISoulseekFileFactory soulseekFileFactory = null) + public ShareScanner( + int workerCount, + IShareRepository shareRepository, + ISoulseekFileFactory soulseekFileFactory = null) { WorkerCount = workerCount; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); - Repository = new ShareRepository(Program.ConnectionStrings.Shares); + Repository = shareRepository; } /// @@ -123,7 +126,7 @@ 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 (!ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares)) + if (!Repository.TryValidate()) { Log.Warning("Shared file cache missing or invalid. Re-creating prior to scan."); Repository.Create(discardExisting: true); @@ -324,10 +327,6 @@ namespace slskd.Shares Repository.UpdateScan(timestamp, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); - Log.Debug("Backing up shared file cache database..."); - Repository.BackupTo(Program.ConnectionStrings.SharesBackup); - Log.Debug("Shared file cache database backup complete"); - var directoryCount = Repository.CountDirectories(); var fileCount = Repository.CountFiles(); diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index b44b79ff..8853707e 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -48,8 +48,6 @@ namespace slskd.Shares ConnectionStringFactory = shareConnectionStringFactory; CacheStorageMode = optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum(); - Scanner = scanner ?? new ShareScanner( - workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers); Scanner.StateMonitor.OnChange(cacheState => { @@ -82,6 +80,10 @@ namespace slskd.Shares Repository = new SqliteShareRepository(ConnectionString); + Scanner = scanner ?? new ShareScanner( + shareRepository: Repository, + workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers); + OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); @@ -258,9 +260,13 @@ namespace slskd.Shares /// /// The operation context. /// Thrown when a scan is already in progress. - public Task ScanAsync() + public async Task ScanAsync() { - return Scanner.ScanAsync(Shares, OptionsMonitor.CurrentValue.Shares); + await Scanner.ScanAsync(Shares, OptionsMonitor.CurrentValue.Shares); + + Log.Debug("Backing up shared file cache database..."); + Repository.BackupTo(BackupConnectionString); + Log.Debug("Shared file cache database backup complete"); } /// @@ -306,7 +312,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (SqliteShareRepository.TryValidateDatabase(BackupConnectionString)) + if (Repository.TryValidate(BackupConnectionString)) { Log.Information("Share cache backup validated. Attempting to restore..."); @@ -324,7 +330,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (SqliteShareRepository.TryValidateDatabase(ConnectionString)) + if (Repository.TryValidate(ConnectionString)) { // no-op } @@ -332,7 +338,7 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (SqliteShareRepository.TryValidateDatabase(BackupConnectionString)) + if (Repository.TryValidate(BackupConnectionString)) { Log.Information("Share cache backup validated. Attempting to restore..."); diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 6a91ef82..737c6954 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -47,19 +47,14 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Attempts to validate the database at the specified . + /// Attempts to validate the database at the specified , or the + /// default . /// /// 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) + public bool TryValidate(string connectionString = null) { - if (connectionString == null) - { - throw new ArgumentNullException(nameof(connectionString), "A connection string is required"); - } - - var log = Serilog.Log.ForContext(); + connectionString ??= ConnectionString; // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' @@ -78,7 +73,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(); @@ -101,7 +96,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); } } @@ -117,7 +112,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; } } -- cgit v1.2.3 From 528f3537c630fe1e0e2d8ce991a388731ffb9b1c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Oct 2022 18:35:20 -0500 Subject: fix bug --- src/slskd/Shares/ShareService.cs | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 8853707e..94940a71 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -48,6 +48,22 @@ namespace slskd.Shares ConnectionStringFactory = shareConnectionStringFactory; CacheStorageMode = optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum(); + if (CacheStorageMode == StorageMode.Memory) + { + ConnectionString = ConnectionStringFactory.CreateFromMemory("shares"); + } + else + { + ConnectionString = ConnectionStringFactory.CreateFromFile("shares"); + } + + BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile("shares"); + + Repository = new SqliteShareRepository(ConnectionString); + + Scanner = scanner ?? new ShareScanner( + shareRepository: Repository, + workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers); Scanner.StateMonitor.OnChange(cacheState => { @@ -67,23 +83,6 @@ namespace slskd.Shares }); }); - if (CacheStorageMode == StorageMode.Memory) - { - ConnectionString = ConnectionStringFactory.CreateFromMemory("shares"); - } - else - { - ConnectionString = ConnectionStringFactory.CreateFromFile("shares"); - } - - BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile("shares"); - - Repository = new SqliteShareRepository(ConnectionString); - - Scanner = scanner ?? new ShareScanner( - shareRepository: Repository, - workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers); - OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); -- cgit v1.2.3 From 1e87c47a84ab5b2188fb34aa642b8bae123dc2d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 13 Oct 2022 09:42:06 -0500 Subject: add Host types --- src/slskd/Shares/Types/Host.cs | 69 +++++++++++++++++++++++++++++++++++++ src/slskd/Shares/Types/HostState.cs | 35 +++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 src/slskd/Shares/Types/Host.cs create mode 100644 src/slskd/Shares/Types/HostState.cs diff --git a/src/slskd/Shares/Types/Host.cs b/src/slskd/Shares/Types/Host.cs new file mode 100644 index 00000000..45706b23 --- /dev/null +++ b/src/slskd/Shares/Types/Host.cs @@ -0,0 +1,69 @@ +// +// 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.Collections.Generic; + using System.Linq; + + /// + /// A share host. + /// + public class Host + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the host. + /// The collection of hosted shares. + /// The initial state of the host. + public Host(string name, IEnumerable shares = null, HostState state = HostState.Offline) + { + Name = name; + Shares = shares ?? Enumerable.Empty(); + State = state; + } + + /// + /// Gets the name of the host. + /// + /// Corresponds to the configured of the host. + public string Name { get; } + + /// + /// Gets the collection of hosted shares. + /// + public IEnumerable Shares { get; private set; } + + /// + /// Gets the host state. + /// + public HostState State { get; private set; } + + /// + /// Sets the hosted shares for the host. + /// + /// The collection of shares. + public void SetShares(IEnumerable shares) => Shares = shares; + + /// + /// Sets the state of the host. + /// + /// The new state. + public void SetState(HostState state) => State = state; + } +} \ No newline at end of file diff --git a/src/slskd/Shares/Types/HostState.cs b/src/slskd/Shares/Types/HostState.cs new file mode 100644 index 00000000..b10074d3 --- /dev/null +++ b/src/slskd/Shares/Types/HostState.cs @@ -0,0 +1,35 @@ +// +// 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 +{ + /// + /// The state of a share host. + /// + public enum HostState + { + /// + /// Offline; unable to service requests. + /// + Offline = 0, + + /// + /// Online; able to service requests. + /// + Online = 1, + } +} -- cgit v1.2.3 From 43c19eac0b258c852fc10d017daf1ee010f8cdcc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 13 Oct 2022 09:43:17 -0500 Subject: differentiate read and read/write repositories. add host collection --- src/slskd/Program.cs | 7 +- .../Shares/API/Controllers/SharesController.cs | 6 +- src/slskd/Shares/IReadOnlyShareRepository.cs | 60 +------------- src/slskd/Shares/IReadWriteShareRepository.cs | 96 ++++++++++++++++++++++ src/slskd/Shares/IShareRepository.cs | 83 ++++++++----------- src/slskd/Shares/IShareService.cs | 20 +---- src/slskd/Shares/ShareScanner.cs | 4 +- src/slskd/Shares/ShareService.cs | 91 +++++++++----------- src/slskd/Shares/SqliteShareRepository.cs | 2 +- 9 files changed, 183 insertions(+), 186 deletions(-) create mode 100644 src/slskd/Shares/IReadWriteShareRepository.cs diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 44558e85..e744ac54 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -39,7 +39,6 @@ namespace slskd using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ApiExplorer; - using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -519,9 +518,9 @@ namespace slskd services.AddSingleton(); services.AddSingleton(new ShareConnectionStringFactory( - createFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, name)}.db;Cache=shared", - createFromMemory: (name) => $"file:{name}?mode=memory", - createBackupFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, name)}.db.bak;")); + createFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, $"shares.{name}")}.db;Cache=shared", + createFromMemory: (name) => $"file:shares.{name}?mode=memory", + createBackupFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, $"shares.{name}")}.db.bak;")); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index d07e8eed..671e8992 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -58,7 +58,7 @@ namespace slskd.Shares.API { var shares = new List(); - foreach (var share in Shares.Shares) + foreach (var share in Shares.Hosts.SelectMany(host => host.Shares)) { var (directories, files) = await Shares.SummarizeShareAsync(share); @@ -91,7 +91,7 @@ namespace slskd.Shares.API [ProducesResponseType(404)] public async Task Get(string id) { - var share = Shares.Shares.FirstOrDefault(share => share.Id == id); + var share = Shares.Hosts.SelectMany(host => host.Shares).FirstOrDefault(share => share.Id == id); if (share == default) { @@ -141,7 +141,7 @@ namespace slskd.Shares.API [ProducesResponseType(404)] public async Task BrowseShare(string id) { - var share = Shares.Shares.FirstOrDefault(share => share.Id == id); + var share = Shares.Hosts.SelectMany(host => host.Shares).FirstOrDefault(share => share.Id == id); if (share == default) { diff --git a/src/slskd/Shares/IReadOnlyShareRepository.cs b/src/slskd/Shares/IReadOnlyShareRepository.cs index 9822f536..fff587ad 100644 --- a/src/slskd/Shares/IReadOnlyShareRepository.cs +++ b/src/slskd/Shares/IReadOnlyShareRepository.cs @@ -17,68 +17,10 @@ namespace slskd.Shares { - using System.Collections.Generic; - using Soulseek; - /// /// Read-only persistent storage of shared files and metadata. /// - public interface IReadOnlyShareRepository + public interface IReadOnlyShareRepository : IShareRepository { - /// - /// Gets the connection string for this repository. - /// - 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); - - /// - /// 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); - - /// - /// Finds the filename of the file matching the specified . - /// - /// The fully qualified remote path of the file. - /// The filename, if found. - string FindFilename(string maskedFilename); - - /// - /// Lists all directories. - /// - /// The optional directory prefix used for listing subdirectories. - /// The list of directories. - IEnumerable ListDirectories(string parentDirectory = null); - - /// - /// 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); - - /// - /// Searches the database for files matching the specified . - /// - /// The search query. - /// The list of matching files. - IEnumerable Search(SearchQuery query); - - /// - /// Attempts to validate the database at the specified , or the - /// default . - /// - /// The connection string of the database to validate. - /// A value indicating whether the database is valid. - bool TryValidate(string connectionString = null); } } diff --git a/src/slskd/Shares/IReadWriteShareRepository.cs b/src/slskd/Shares/IReadWriteShareRepository.cs new file mode 100644 index 00000000..c6701753 --- /dev/null +++ b/src/slskd/Shares/IReadWriteShareRepository.cs @@ -0,0 +1,96 @@ +// +// 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 Soulseek; + + /// + /// Writeable persistent storage of shared files and metadata. + /// + public interface IReadWriteShareRepository : IShareRepository + { + + /// + /// 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); + + /// + /// Inserts a directory. + /// + /// The fully qualified local name of the directory. + /// The timestamp to assign to the record. + void InsertDirectory(string name, long timestamp); + + /// + /// 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, File file, long timestamp); + + /// + /// Inserts a scan record at the specified . + /// + /// The timestamp associated with the scan. + /// The options snapshot at the start of the scan. + void InsertScan(long timestamp, Options.SharesOptions options); + + /// + /// Backs the current database up to the database at the specified . + /// + /// The connection string of the destination database. + void BackupTo(string connectionString); + + /// + /// Restores the current database from the database at the specified . + /// + /// The connection string of the source database. + void RestoreFrom(string connectionString); + + /// + /// 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); + + /// + /// 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); + + /// + /// Updates the scan started at the specified to set the . + /// + /// The timestamp associated with the scan. + /// The timestamp at the conclusion of the scan. + void UpdateScan(long timestamp, long end); + } +} \ No newline at end of file diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs index 59c9537e..87c2c386 100644 --- a/src/slskd/Shares/IShareRepository.cs +++ b/src/slskd/Shares/IShareRepository.cs @@ -17,79 +17,68 @@ namespace slskd.Shares { - using System; + using System.Collections.Generic; using Soulseek; /// - /// Writeable persistent storage of shared files and metadata. + /// Persistent storage of shared files and metadata. /// - public interface IShareRepository : IReadOnlyShareRepository + public interface IShareRepository { /// - /// Creates a new database. + /// Gets the connection string for this repository. /// - /// - /// 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); + string ConnectionString { get; } /// - /// Inserts a directory. + /// Counts the number of directories in the database. /// - /// The fully qualified local name of the directory. - /// The timestamp to assign to the record. - void InsertDirectory(string name, long timestamp); + /// The optional directory prefix used for counting subdirectories. + /// The number of directories. + int CountDirectories(string parentDirectory = null); /// - /// Inserts a file. + /// Counts the number of files in the database. /// - /// 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, File file, long timestamp); + /// The optional directory prefix used for counting files in a subdirectory. + /// The number of files. + int CountFiles(string parentDirectory = null); /// - /// Inserts a scan record at the specified . + /// Finds the filename of the file matching the specified . /// - /// The timestamp associated with the scan. - /// The options snapshot at the start of the scan. - void InsertScan(long timestamp, Options.SharesOptions options); - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - void BackupTo(string connectionString); + /// The fully qualified remote path of the file. + /// The filename, if found. + string FindFilename(string maskedFilename); /// - /// Restores the current database from the database at the specified . + /// Lists all directories. /// - /// The connection string of the source database. - void RestoreFrom(string connectionString); + /// The optional directory prefix used for listing subdirectories. + /// The list of directories. + IEnumerable ListDirectories(string parentDirectory = null); /// - /// Deletes directory records with a timestamp prior to the specified . + /// Lists all files. /// - /// The timestamp before which to delete directories. - /// The number of records deleted. - long PruneDirectories(long olderThanTimestamp); + /// 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); /// - /// Deletes file records with a timestamp prior to the specified . + /// Searches the database for files matching the specified . /// - /// The timestamp before which to delete files. - /// The number of records deleted. - long PruneFiles(long olderThanTimestamp); + /// The search query. + /// The list of matching files. + IEnumerable Search(SearchQuery query); /// - /// Updates the scan started at the specified to set the . + /// Attempts to validate the database at the specified , or the + /// default . /// - /// The timestamp associated with the scan. - /// The timestamp at the conclusion of the scan. - void UpdateScan(long timestamp, long end); + /// The connection string of the database to validate. + /// A value indicating whether the database is valid. + bool TryValidate(string connectionString = null); } -} \ No newline at end of file +} diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 3ec5fd56..821ac20e 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -29,27 +29,15 @@ namespace slskd.Shares public interface IShareService { /// - /// Gets the list of configured shares. + /// Gets the list of share hosts. /// - IReadOnlyList Shares { get; } + IReadOnlyList Hosts { get; } /// /// Gets the state monitor for the service. /// public IStateMonitor StateMonitor { get; } - /// - /// Adds the shares associated with the specified . - /// - /// The name of the agent. - void AddAgentShares(string agent); - - /// - /// Remotes the shares associated with the specified . - /// - /// The name of the agent. - void RemoveAgentShares(string agent); - /// /// Returns the entire contents of the share. /// @@ -82,7 +70,7 @@ namespace slskd.Shares Task> SearchAsync(SearchQuery query); /// - /// Scans the configured shares. + /// Scans the configured shares on the local host. /// /// The operation context. /// Thrown when a scan is already in progress. @@ -96,7 +84,7 @@ namespace slskd.Shares Task<(int Directories, int Files)> SummarizeShareAsync(Share share); /// - /// Cancels the currently running scan, if one is running. + /// Cancels the currently running scan on the local host, if one is running. /// /// A value indicating whether a scan was cancelled. bool TryCancelScan(); diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 7a174396..f5e7e52d 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -67,7 +67,7 @@ namespace slskd.Shares /// public ShareScanner( int workerCount, - IShareRepository shareRepository, + IReadWriteShareRepository shareRepository, ISoulseekFileFactory soulseekFileFactory = null) { WorkerCount = workerCount; @@ -87,7 +87,7 @@ namespace slskd.Shares private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private CancellationTokenSource CancellationTokenSource { get; set; } - private IShareRepository Repository { get; } + private IReadWriteShareRepository Repository { get; } /// /// Scans the configured shares and fills the cache. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 94940a71..d36a7d20 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -45,25 +45,30 @@ namespace slskd.Shares IOptionsMonitor optionsMonitor, IShareScanner scanner = null) { + var options = optionsMonitor.CurrentValue; + ConnectionStringFactory = shareConnectionStringFactory; - CacheStorageMode = optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum(); + CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum(); if (CacheStorageMode == StorageMode.Memory) { - ConnectionString = ConnectionStringFactory.CreateFromMemory("shares"); + ConnectionString = ConnectionStringFactory.CreateFromMemory(options.InstanceName); } else { - ConnectionString = ConnectionStringFactory.CreateFromFile("shares"); + ConnectionString = ConnectionStringFactory.CreateFromFile(options.InstanceName); } - BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile("shares"); + BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile(options.InstanceName); + + var host = new Host(options.InstanceName, state: HostState.Online); + var repository = new SqliteShareRepository(ConnectionString); - Repository = new SqliteShareRepository(ConnectionString); + HostDictionary.TryAdd(options.InstanceName, (host, repository)); Scanner = scanner ?? new ShareScanner( - shareRepository: Repository, - workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers); + shareRepository: repository, + workerCount: options.Shares.Cache.Workers); Scanner.StateMonitor.OnChange(cacheState => { @@ -92,9 +97,9 @@ namespace slskd.Shares } /// - /// Gets the list of configured shares. + /// Gets the list of share hosts. /// - public IReadOnlyList Shares => SharesList.AsReadOnly(); + public IReadOnlyList Hosts => HostDictionary.Values.Select(v => v.Host).ToList().AsReadOnly(); /// /// Gets the state monitor for the service. @@ -105,40 +110,20 @@ namespace slskd.Shares private string BackupConnectionString { get; } private ShareConnectionStringFactory ConnectionStringFactory { get; } private IShareScanner Scanner { get; } - private IShareRepository Repository { get; } private string LastOptionsHash { get; set; } private IOptionsMonitor OptionsMonitor { get; } - private List SharesList { get; set; } = new List(); + private ConcurrentDictionary HostDictionary { get; set; } = new(); private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private ConcurrentDictionary AgentRepositories { get; } = new(); - - /// - /// Adds the shares associated with the specified . - /// - /// The name of the agent. - public void AddAgentShares(string agent) + private (Host Host, IReadWriteShareRepository Repository) LocalHost { - if (string.IsNullOrEmpty(agent)) + get { - throw new ArgumentNullException(nameof(agent)); + HostDictionary.TryGetValue(OptionsMonitor.CurrentValue.InstanceName, out var record); + return (record.Host, (IReadWriteShareRepository)record.Repository); } - - AgentRepositories.AddOrUpdate( - key: agent, - addValue: new SqliteShareRepository(BuildConnectionString(agent)), - updateValueFactory: (_, repository) => new SqliteShareRepository(BuildConnectionString(agent))); - } - - /// - /// Remotes the shares associated with the specified . - /// - /// The name of the agent. - public void RemoveAgentShares(string agent) - { - AgentRepositories.TryRemove(agent, out _); } /// @@ -161,13 +146,13 @@ namespace slskd.Shares // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the // files. if not they'll be left as is. - foreach (var directory in Repository.ListDirectories(prefix)) + foreach (var directory in LocalHost.Repository.ListDirectories(prefix)) { var name = directory.NormalizePathForSoulseek(); directories.TryAdd(name, new Directory(name)); } - var files = Repository.ListFiles(prefix, includeFullPath: true); + var files = LocalHost.Repository.ListFiles(prefix, includeFullPath: true); var groups = files .GroupBy(file => Path.GetDirectoryName(file.Filename)) @@ -202,7 +187,7 @@ namespace slskd.Shares { var localPath = directory.LocalizePath(); - var files = Repository.ListFiles(localPath); + var files = LocalHost.Repository.ListFiles(localPath); return Task.FromResult(new Directory(directory, files)); } @@ -218,7 +203,7 @@ namespace slskd.Shares /// public Task ResolveFileAsync(string remoteFilename) { - var resolvedFilename = Repository.FindFilename(remoteFilename.LocalizePath()); + var resolvedFilename = LocalHost.Repository.FindFilename(remoteFilename.LocalizePath()); if (string.IsNullOrEmpty(resolvedFilename)) { @@ -244,7 +229,7 @@ namespace slskd.Shares /// The matching files. public Task> SearchAsync(SearchQuery query) { - var results = Repository.Search(query); + var results = LocalHost.Repository.Search(query); return Task.FromResult(results.Select(r => new File( r.Code, @@ -261,10 +246,10 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. public async Task ScanAsync() { - await Scanner.ScanAsync(Shares, OptionsMonitor.CurrentValue.Shares); + await Scanner.ScanAsync(LocalHost.Host.Shares, OptionsMonitor.CurrentValue.Shares); Log.Debug("Backing up shared file cache database..."); - Repository.BackupTo(BackupConnectionString); + LocalHost.Repository.BackupTo(BackupConnectionString); Log.Debug("Shared file cache database backup complete"); } @@ -277,8 +262,8 @@ namespace slskd.Shares { var prefix = share.RemotePath + Path.DirectorySeparatorChar; - var dirs = Repository.CountDirectories(prefix); - var files = Repository.CountFiles(prefix); + var dirs = LocalHost.Repository.CountDirectories(prefix); + var files = LocalHost.Repository.CountFiles(prefix); return Task.FromResult((dirs, files)); } @@ -311,11 +296,11 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (Repository.TryValidate(BackupConnectionString)) + if (LocalHost.Repository.TryValidate(BackupConnectionString)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Repository.RestoreFrom(connectionString: BackupConnectionString); + LocalHost.Repository.RestoreFrom(connectionString: BackupConnectionString); Log.Information("Share cache successfully restored from backup"); } @@ -329,7 +314,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (Repository.TryValidate(ConnectionString)) + if (LocalHost.Repository.TryValidate(ConnectionString)) { // no-op } @@ -337,11 +322,11 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (Repository.TryValidate(BackupConnectionString)) + if (LocalHost.Repository.TryValidate(BackupConnectionString)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Repository.RestoreFrom(connectionString: BackupConnectionString); + LocalHost.Repository.RestoreFrom(connectionString: BackupConnectionString); Log.Information("Share cache successfully restored from backup"); } @@ -366,8 +351,8 @@ namespace slskd.Shares Faulted = false, Ready = true, ScanProgress = 1, - Directories = Repository.CountDirectories(), - Files = Repository.CountFiles(), + Directories = LocalHost.Repository.CountDirectories(), + Files = LocalHost.Repository.CountFiles(), }); } catch (Exception ex) @@ -387,8 +372,6 @@ namespace slskd.Shares } } - private string BuildConnectionString(string agent = null) => $"Data Source={agent}{(!string.IsNullOrEmpty(agent) ? "." : string.Empty)}shares.db"; - private void Configure(Options options) { SyncRoot.Wait(); @@ -405,11 +388,11 @@ namespace slskd.Shares var shares = options.Shares.Directories .Select(share => share.TrimEnd('/', '\\')) .ToHashSet() // remove duplicates - .Select(share => new Share(share)) // convert to Shares + .Select(share => new Share(host: options.InstanceName, share)) // convert to Shares .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent .ToList(); - SharesList = shares; + LocalHost.Host.SetShares(shares); State.SetValue(state => state with { ScanPending = true }); diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 737c6954..bb00f420 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -28,7 +28,7 @@ namespace slskd.Shares /// /// Persistent storage of shared files and metadata. /// - public class SqliteShareRepository : IShareRepository + public class SqliteShareRepository : IReadWriteShareRepository { /// /// Initializes a new instance of the class. -- cgit v1.2.3 From d601ae74def72dbef7baa73c8c45390b186f61c8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 13 Oct 2022 10:46:00 -0500 Subject: add HostType --- src/slskd/Shares/Types/Host.cs | 9 ++++++++- src/slskd/Shares/Types/HostType.cs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/slskd/Shares/Types/HostType.cs diff --git a/src/slskd/Shares/Types/Host.cs b/src/slskd/Shares/Types/Host.cs index 45706b23..db68c48e 100644 --- a/src/slskd/Shares/Types/Host.cs +++ b/src/slskd/Shares/Types/Host.cs @@ -29,11 +29,13 @@ namespace slskd.Shares /// Initializes a new instance of the class. /// /// The name of the host. + /// The type of the host. /// The collection of hosted shares. /// The initial state of the host. - public Host(string name, IEnumerable shares = null, HostState state = HostState.Offline) + public Host(string name, HostType type, IEnumerable shares = null, HostState state = HostState.Offline) { Name = name; + Type = type; Shares = shares ?? Enumerable.Empty(); State = state; } @@ -54,6 +56,11 @@ namespace slskd.Shares /// public HostState State { get; private set; } + /// + /// Gets the host type. + /// + public HostType Type { get; } + /// /// Sets the hosted shares for the host. /// diff --git a/src/slskd/Shares/Types/HostType.cs b/src/slskd/Shares/Types/HostType.cs new file mode 100644 index 00000000..6a892dff --- /dev/null +++ b/src/slskd/Shares/Types/HostType.cs @@ -0,0 +1,35 @@ +// +// 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 +{ + /// + /// The type of host. + /// + public enum HostType + { + /// + /// Local. + /// + Local = 0, + + /// + /// Remote; shares are hosted by an Agent. + /// + Remote = 1, + } +} -- cgit v1.2.3 From a670caf1ae399448e1175a1f4e2032b22e580c4b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 13 Oct 2022 12:02:23 -0500 Subject: refactor Local usage --- src/slskd/Shares/ShareService.cs | 53 +++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 31 deletions(-) diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index d36a7d20..56be06e2 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -61,10 +61,10 @@ namespace slskd.Shares BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile(options.InstanceName); - var host = new Host(options.InstanceName, state: HostState.Online); + var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online); var repository = new SqliteShareRepository(ConnectionString); - HostDictionary.TryAdd(options.InstanceName, (host, repository)); + Local = (host, repository); Scanner = scanner ?? new ShareScanner( shareRepository: repository, @@ -99,7 +99,7 @@ namespace slskd.Shares /// /// Gets the list of share hosts. /// - public IReadOnlyList Hosts => HostDictionary.Values.Select(v => v.Host).ToList().AsReadOnly(); + public IReadOnlyList Hosts => HostDictionary.Values.Select(v => v.Host).Prepend(Local.Host).ToList().AsReadOnly(); /// /// Gets the state monitor for the service. @@ -117,14 +117,7 @@ namespace slskd.Shares private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private (Host Host, IReadWriteShareRepository Repository) LocalHost - { - get - { - HostDictionary.TryGetValue(OptionsMonitor.CurrentValue.InstanceName, out var record); - return (record.Host, (IReadWriteShareRepository)record.Repository); - } - } + private (Host Host, IReadWriteShareRepository Repository) Local { get; set; } /// /// Returns the entire contents of the share. @@ -146,13 +139,13 @@ namespace slskd.Shares // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the // files. if not they'll be left as is. - foreach (var directory in LocalHost.Repository.ListDirectories(prefix)) + foreach (var directory in Local.Repository.ListDirectories(prefix)) { var name = directory.NormalizePathForSoulseek(); directories.TryAdd(name, new Directory(name)); } - var files = LocalHost.Repository.ListFiles(prefix, includeFullPath: true); + var files = Local.Repository.ListFiles(prefix, includeFullPath: true); var groups = files .GroupBy(file => Path.GetDirectoryName(file.Filename)) @@ -187,7 +180,7 @@ namespace slskd.Shares { var localPath = directory.LocalizePath(); - var files = LocalHost.Repository.ListFiles(localPath); + var files = Local.Repository.ListFiles(localPath); return Task.FromResult(new Directory(directory, files)); } @@ -203,7 +196,7 @@ namespace slskd.Shares /// public Task ResolveFileAsync(string remoteFilename) { - var resolvedFilename = LocalHost.Repository.FindFilename(remoteFilename.LocalizePath()); + var resolvedFilename = Local.Repository.FindFilename(remoteFilename.LocalizePath()); if (string.IsNullOrEmpty(resolvedFilename)) { @@ -229,7 +222,7 @@ namespace slskd.Shares /// The matching files. public Task> SearchAsync(SearchQuery query) { - var results = LocalHost.Repository.Search(query); + var results = Local.Repository.Search(query); return Task.FromResult(results.Select(r => new File( r.Code, @@ -246,10 +239,10 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. public async Task ScanAsync() { - await Scanner.ScanAsync(LocalHost.Host.Shares, OptionsMonitor.CurrentValue.Shares); + await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares); Log.Debug("Backing up shared file cache database..."); - LocalHost.Repository.BackupTo(BackupConnectionString); + Local.Repository.BackupTo(BackupConnectionString); Log.Debug("Shared file cache database backup complete"); } @@ -262,8 +255,8 @@ namespace slskd.Shares { var prefix = share.RemotePath + Path.DirectorySeparatorChar; - var dirs = LocalHost.Repository.CountDirectories(prefix); - var files = LocalHost.Repository.CountFiles(prefix); + var dirs = Local.Repository.CountDirectories(prefix); + var files = Local.Repository.CountFiles(prefix); return Task.FromResult((dirs, files)); } @@ -296,11 +289,11 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (LocalHost.Repository.TryValidate(BackupConnectionString)) + if (Local.Repository.TryValidate(BackupConnectionString)) { Log.Information("Share cache backup validated. Attempting to restore..."); - LocalHost.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(connectionString: BackupConnectionString); Log.Information("Share cache successfully restored from backup"); } @@ -314,7 +307,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (LocalHost.Repository.TryValidate(ConnectionString)) + if (Local.Repository.TryValidate(ConnectionString)) { // no-op } @@ -322,11 +315,11 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (LocalHost.Repository.TryValidate(BackupConnectionString)) + if (Local.Repository.TryValidate(BackupConnectionString)) { Log.Information("Share cache backup validated. Attempting to restore..."); - LocalHost.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(connectionString: BackupConnectionString); Log.Information("Share cache successfully restored from backup"); } @@ -351,8 +344,8 @@ namespace slskd.Shares Faulted = false, Ready = true, ScanProgress = 1, - Directories = LocalHost.Repository.CountDirectories(), - Files = LocalHost.Repository.CountFiles(), + Directories = Local.Repository.CountDirectories(), + Files = Local.Repository.CountFiles(), }); } catch (Exception ex) @@ -388,13 +381,11 @@ namespace slskd.Shares var shares = options.Shares.Directories .Select(share => share.TrimEnd('/', '\\')) .ToHashSet() // remove duplicates - .Select(share => new Share(host: options.InstanceName, share)) // convert to Shares + .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(); - LocalHost.Host.SetShares(shares); - - State.SetValue(state => state with { ScanPending = true }); + Local.Host.SetShares(shares); LastOptionsHash = optionsHash; } -- cgit v1.2.3 From 69dfdc9830324965aa5cc4f30d16a8cb60ff39f3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 13 Oct 2022 20:31:42 -0500 Subject: use a record --- src/slskd/Shares/Types/Host.cs | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/src/slskd/Shares/Types/Host.cs b/src/slskd/Shares/Types/Host.cs index db68c48e..3c5c9f9f 100644 --- a/src/slskd/Shares/Types/Host.cs +++ b/src/slskd/Shares/Types/Host.cs @@ -23,7 +23,7 @@ namespace slskd.Shares /// /// A share host. /// - public class Host + public record Host { /// /// Initializes a new instance of the class. @@ -49,28 +49,16 @@ namespace slskd.Shares /// /// Gets the collection of hosted shares. /// - public IEnumerable Shares { get; private set; } + public IEnumerable Shares { get; init; } /// /// Gets the host state. /// - public HostState State { get; private set; } + public HostState State { get; init; } /// /// Gets the host type. /// public HostType Type { get; } - - /// - /// Sets the hosted shares for the host. - /// - /// The collection of shares. - public void SetShares(IEnumerable shares) => Shares = shares; - - /// - /// Sets the state of the host. - /// - /// The new state. - public void SetState(HostState state) => State = state; } } \ No newline at end of file -- cgit v1.2.3 From 6d4d92827664c0ca0d951b19b0a5cbdfd1d0cebb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 13 Oct 2022 20:32:40 -0500 Subject: use all repositories to service lookups --- src/slskd/Shares/IShareService.cs | 8 +++++- src/slskd/Shares/ShareService.cs | 41 +++++++++++++++++++++++++------ src/slskd/Shares/SqliteShareRepository.cs | 2 +- 3 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 821ac20e..9d0ba487 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -36,7 +36,13 @@ namespace slskd.Shares /// /// Gets the state monitor for the service. /// - public IStateMonitor StateMonitor { get; } + IStateMonitor StateMonitor { get; } + + /// + /// Adds a new, or updates an existing, share host. + /// + /// The host to add or update. + void AddOrUpdateHost(Host host); /// /// Returns the entire contents of the share. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 56be06e2..12131eae 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -66,6 +66,8 @@ namespace slskd.Shares Local = (host, repository); + AllRepositories = new List(new[] { repository }); + Scanner = scanner ?? new ShareScanner( shareRepository: repository, workerCount: options.Shares.Cache.Workers); @@ -118,6 +120,24 @@ namespace slskd.Shares private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private (Host Host, IReadWriteShareRepository Repository) Local { get; set; } + private IEnumerable AllRepositories { get; set; } + + /// + /// Adds a new, or updates an existing, share host. + /// + /// The host to add or update. + public void AddOrUpdateHost(Host host) + { + HostDictionary.AddOrUpdate( + key: host.Name, + addValueFactory: (key) => (host, new SqliteShareRepository(ConnectionStringFactory.CreateFromFile(host.Name))), + updateValueFactory: (_, existing) => (host, existing.Repository)); + + AllRepositories = HostDictionary.Values + .Where(value => value.Host.State == HostState.Online) + .Select(value => value.Repository) + .Prepend(Local.Repository); + } /// /// Returns the entire contents of the share. @@ -139,13 +159,13 @@ namespace slskd.Shares // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the // files. if not they'll be left as is. - foreach (var directory in Local.Repository.ListDirectories(prefix)) + foreach (var directory in AllRepositories.SelectMany(r => r.ListDirectories(prefix))) { var name = directory.NormalizePathForSoulseek(); directories.TryAdd(name, new Directory(name)); } - var files = Local.Repository.ListFiles(prefix, includeFullPath: true); + var files = AllRepositories.SelectMany(r => r.ListFiles(prefix, includeFullPath: true)); var groups = files .GroupBy(file => Path.GetDirectoryName(file.Filename)) @@ -180,7 +200,7 @@ namespace slskd.Shares { var localPath = directory.LocalizePath(); - var files = Local.Repository.ListFiles(localPath); + var files = AllRepositories.SelectMany(r => r.ListFiles(localPath)); return Task.FromResult(new Directory(directory, files)); } @@ -196,7 +216,9 @@ namespace slskd.Shares /// public Task ResolveFileAsync(string remoteFilename) { - var resolvedFilename = Local.Repository.FindFilename(remoteFilename.LocalizePath()); + var resolvedFilename = AllRepositories + .Select(r => r.FindFilename(remoteFilename.LocalizePath())) + .FirstOrDefault(r => !string.IsNullOrEmpty(r)); if (string.IsNullOrEmpty(resolvedFilename)) { @@ -222,7 +244,7 @@ namespace slskd.Shares /// The matching files. public Task> SearchAsync(SearchQuery query) { - var results = Local.Repository.Search(query); + var results = AllRepositories.SelectMany(r => r.Search(query)); return Task.FromResult(results.Select(r => new File( r.Code, @@ -255,8 +277,8 @@ namespace slskd.Shares { var prefix = share.RemotePath + Path.DirectorySeparatorChar; - var dirs = Local.Repository.CountDirectories(prefix); - var files = Local.Repository.CountFiles(prefix); + var dirs = AllRepositories.Select(r => r.CountDirectories(prefix)).Sum(); + var files = AllRepositories.Select(r => r.CountFiles(prefix)).Sum(); return Task.FromResult((dirs, files)); } @@ -385,7 +407,10 @@ namespace slskd.Shares .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent .ToList(); - Local.Host.SetShares(shares); + Local = (Local.Host with { Shares = shares }, Local.Repository); + + // todo: initialize agent hosts + // todo: don't destroy or overwrite existing hosts! LastOptionsHash = optionsHash; } diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index bb00f420..28788c3f 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -229,7 +229,7 @@ namespace slskd.Shares /// /// The fully qualified remote path of the file. /// The filename, if found. - public string FindFilename (string maskedFilename) + public string FindFilename(string maskedFilename) { using var conn = GetConnection(); using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn); -- cgit v1.2.3