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 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) (limited to 'src/slskd/Program.cs') 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(); -- 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(-) (limited to 'src/slskd/Program.cs') 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(-) (limited to 'src/slskd/Program.cs') 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 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 (limited to 'src/slskd/Program.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