aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-10-14 08:41:12 -0500
committerGitHub <noreply@github.com>2022-10-14 08:41:12 -0500
commit593308d4e786cd569e3a683f5b02b8f13aa39b23 (patch)
tree3555863f90065a615ce4f59fcc58d7dcd818e8ed /src/slskd
parentdc1e6a63db9ff87813633963b2f3d7acc60d2709 (diff)
parentfe03a44d359e3bcd39447609a0aa15b8492e5306 (diff)
downloadslskd-593308d4e786cd569e3a683f5b02b8f13aa39b23.tar.gz
Merge pull request #695 from slskd/multi-shares
Refactor some internals to allow multiple share repositories to be used
Diffstat (limited to 'src/slskd')
-rw-r--r--src/slskd/Program.cs35
-rw-r--r--src/slskd/Shares/API/Controllers/SharesController.cs6
-rw-r--r--src/slskd/Shares/IReadOnlyShareRepository.cs (renamed from src/slskd/Core/ConnectionStrings.cs)12
-rw-r--r--src/slskd/Shares/IReadWriteShareRepository.cs96
-rw-r--r--src/slskd/Shares/IShareRepository.cs84
-rw-r--r--src/slskd/Shares/IShareService.cs16
-rw-r--r--src/slskd/Shares/ShareConnectionStringFactory.cs58
-rw-r--r--src/slskd/Shares/ShareScanner.cs15
-rw-r--r--src/slskd/Shares/ShareService.cs103
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs (renamed from src/slskd/Shares/ShareRepository.cs)162
-rw-r--r--src/slskd/Shares/Types/Host.cs64
-rw-r--r--src/slskd/Shares/Types/HostState.cs35
-rw-r--r--src/slskd/Shares/Types/HostType.cs35
13 files changed, 501 insertions, 220 deletions
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 8b816f48..e744ac54 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -162,11 +162,6 @@ namespace slskd
public static string ConfigurationFile { get; private set; } = null;
/// <summary>
- /// Gets the connection strings for application databases.
- /// </summary>
- public static ConnectionStrings ConnectionStrings { get; private set; } = null;
-
- /// <summary>
/// Gets the path where persistent data is saved.
/// </summary>
public static string DataDirectory { get; private set; } = null;
@@ -395,28 +390,6 @@ namespace slskd
RecreateConfigurationFileIfMissing(ConfigurationFile);
- // configure connection strings and configure SQLite
- string shareDbDataSource = default;
-
- if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum<StorageMode>() == StorageMode.Disk)
- {
- Log.Information("Using on-disk shared file cache");
- shareDbDataSource = Path.Combine(DataDirectory, "shares.db");
- }
- else
- {
- Log.Information("Using in-memory shared file cache");
- shareDbDataSource = "file:shares?mode=memory";
- }
-
- ConnectionStrings = new()
- {
- Search = $"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;",
- Transfers = $"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;",
- Shares = $"Data Source={shareDbDataSource};Cache=shared",
- SharesBackup = $"Data Source={Path.Combine(DataDirectory, "shares.db.bak")};",
- };
-
if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki))
{
Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki);
@@ -536,14 +509,18 @@ namespace slskd
services.AddSingleton<IConnectionWatchdog, ConnectionWatchdog>();
- services.AddDbContext<SearchDbContext>(ConnectionStrings.Search);
- services.AddDbContext<TransfersDbContext>(ConnectionStrings.Transfers);
+ services.AddDbContext<SearchDbContext>($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;");
+ services.AddDbContext<TransfersDbContext>($"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;");
services.AddSingleton<IBrowseTracker, BrowseTracker>();
services.AddSingleton<IConversationTracker, ConversationTracker>();
services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
services.AddSingleton<IShareService, ShareService>();
+ services.AddSingleton(new ShareConnectionStringFactory(
+ 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<ISearchService, SearchService>();
services.AddSingleton<IUserService, UserService>();
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<SummarizedShare>();
- 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<IActionResult> 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<IActionResult> 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/Core/ConnectionStrings.cs b/src/slskd/Shares/IReadOnlyShareRepository.cs
index 6afab93f..fff587ad 100644
--- a/src/slskd/Core/ConnectionStrings.cs
+++ b/src/slskd/Shares/IReadOnlyShareRepository.cs
@@ -1,4 +1,4 @@
-// <copyright file="ConnectionStrings.cs" company="slskd Team">
+// <copyright file="IReadOnlyShareRepository.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -15,16 +15,12 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd
+namespace slskd.Shares
{
/// <summary>
- /// Application connection strings.
+ /// Read-only persistent storage of shared files and metadata.
/// </summary>
- public record ConnectionStrings
+ public interface IReadOnlyShareRepository : IShareRepository
{
- public string Transfers { get; init; }
- public string Shares { get; init; }
- public string SharesBackup { get; init; }
- public string Search { get; init; }
}
}
diff --git a/src/slskd/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 file="IReadWriteShareRepository.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Shares
+{
+ using System;
+ using Soulseek;
+
+ /// <summary>
+ /// Writeable persistent storage of shared files and metadata.
+ /// </summary>
+ public interface IReadWriteShareRepository : IShareRepository
+ {
+
+ /// <summary>
+ /// Creates a new database.
+ /// </summary>
+ /// <remarks>
+ /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case
+ /// tables are explicitly dropped prior to creation.
+ /// </remarks>
+ /// <param name="discardExisting">An optional value that determines whether the existing database should be discarded.</param>
+ void Create(bool discardExisting = false);
+
+ /// <summary>
+ /// Inserts a directory.
+ /// </summary>
+ /// <param name="name">The fully qualified local name of the directory.</param>
+ /// <param name="timestamp">The timestamp to assign to the record.</param>
+ void InsertDirectory(string name, long timestamp);
+
+ /// <summary>
+ /// Inserts a file.
+ /// </summary>
+ /// <param name="maskedFilename">The fully qualified remote path of the file.</param>
+ /// <param name="originalFilename">The fully qualified local path of the file.</param>
+ /// <param name="touchedAt">The timestamp at which the file was last modified, according to the host OS.</param>
+ /// <param name="file">The Soulseek.File instance representing the file.</param>
+ /// <param name="timestamp">The timestamp to assign to the record.</param>
+ void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp);
+
+ /// <summary>
+ /// Inserts a scan record at the specified <paramref name="timestamp"/>.
+ /// </summary>
+ /// <param name="timestamp">The timestamp associated with the scan.</param>
+ /// <param name="options">The options snapshot at the start of the scan.</param>
+ void InsertScan(long timestamp, Options.SharesOptions options);
+
+ /// <summary>
+ /// Backs the current database up to the database at the specified <paramref name="connectionString"/>.
+ /// </summary>
+ /// <param name="connectionString">The connection string of the destination database.</param>
+ void BackupTo(string connectionString);
+
+ /// <summary>
+ /// Restores the current database from the database at the specified <paramref name="connectionString"/>.
+ /// </summary>
+ /// <param name="connectionString">The connection string of the source database.</param>
+ void RestoreFrom(string connectionString);
+
+ /// <summary>
+ /// Deletes directory records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>.
+ /// </summary>
+ /// <param name="olderThanTimestamp">The timestamp before which to delete directories.</param>
+ /// <returns>The number of records deleted.</returns>
+ long PruneDirectories(long olderThanTimestamp);
+
+ /// <summary>
+ /// Deletes file records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>.
+ /// </summary>
+ /// <param name="olderThanTimestamp">The timestamp before which to delete files.</param>
+ /// <returns>The number of records deleted.</returns>
+ long PruneFiles(long olderThanTimestamp);
+
+ /// <summary>
+ /// Updates the scan started at the specified <paramref name="timestamp"/> to set the <paramref name="end"/>.
+ /// </summary>
+ /// <param name="timestamp">The timestamp associated with the scan.</param>
+ /// <param name="end">The timestamp at the conclusion of the scan.</param>
+ 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
new file mode 100644
index 00000000..87c2c386
--- /dev/null
+++ b/src/slskd/Shares/IShareRepository.cs
@@ -0,0 +1,84 @@
+// <copyright file="IShareRepository.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Shares
+{
+ using System.Collections.Generic;
+ using Soulseek;
+
+ /// <summary>
+ /// Persistent storage of shared files and metadata.
+ /// </summary>
+ public interface IShareRepository
+ {
+ /// <summary>
+ /// Gets the connection string for this repository.
+ /// </summary>
+ string ConnectionString { get; }
+
+ /// <summary>
+ /// Counts the number of directories in the database.
+ /// </summary>
+ /// <param name="parentDirectory">The optional directory prefix used for counting subdirectories.</param>
+ /// <returns>The number of directories.</returns>
+ int CountDirectories(string parentDirectory = null);
+
+ /// <summary>
+ /// Counts the number of files in the database.
+ /// </summary>
+ /// <param name="parentDirectory">The optional directory prefix used for counting files in a subdirectory.</param>
+ /// <returns>The number of files.</returns>
+ int CountFiles(string parentDirectory = null);
+
+ /// <summary>
+ /// Finds the filename of the file matching the specified <paramref name="maskedFilename"/>.
+ /// </summary>
+ /// <param name="maskedFilename">The fully qualified remote path of the file.</param>
+ /// <returns>The filename, if found.</returns>
+ string FindFilename(string maskedFilename);
+
+ /// <summary>
+ /// Lists all directories.
+ /// </summary>
+ /// <param name="parentDirectory">The optional directory prefix used for listing subdirectories.</param>
+ /// <returns>The list of directories.</returns>
+ IEnumerable<string> ListDirectories(string parentDirectory = null);
+
+ /// <summary>
+ /// Lists all files.
+ /// </summary>
+ /// <param name="parentDirectory">The optional parent directory.</param>
+ /// <param name="includeFullPath">A value indicating whether the fully qualified path should be returned.</param>
+ /// <returns>The list of files.</returns>
+ IEnumerable<File> ListFiles(string parentDirectory = null, bool includeFullPath = false);
+
+ /// <summary>
+ /// Searches the database for files matching the specified <paramref name="query"/>.
+ /// </summary>
+ /// <param name="query">The search query.</param>
+ /// <returns>The list of matching files.</returns>
+ IEnumerable<File> Search(SearchQuery query);
+
+ /// <summary>
+ /// Attempts to validate the database at the specified <paramref name="connectionString"/>, or the
+ /// default <see cref="ConnectionString"/>.
+ /// </summary>
+ /// <param name="connectionString">The connection string of the database to validate.</param>
+ /// <returns>A value indicating whether the database is valid.</returns>
+ bool TryValidate(string connectionString = null);
+ }
+}
diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs
index 2a18f5b3..9d0ba487 100644
--- a/src/slskd/Shares/IShareService.cs
+++ b/src/slskd/Shares/IShareService.cs
@@ -29,14 +29,20 @@ namespace slskd.Shares
public interface IShareService
{
/// <summary>
- /// Gets the list of configured shares.
+ /// Gets the list of share hosts.
/// </summary>
- IReadOnlyList<Share> Shares { get; }
+ IReadOnlyList<Host> Hosts { get; }
/// <summary>
/// Gets the state monitor for the service.
/// </summary>
- public IStateMonitor<ShareState> StateMonitor { get; }
+ IStateMonitor<ShareState> StateMonitor { get; }
+
+ /// <summary>
+ /// Adds a new, or updates an existing, share host.
+ /// </summary>
+ /// <param name="host">The host to add or update.</param>
+ void AddOrUpdateHost(Host host);
/// <summary>
/// Returns the entire contents of the share.
@@ -70,7 +76,7 @@ namespace slskd.Shares
Task<IEnumerable<File>> SearchAsync(SearchQuery query);
/// <summary>
- /// Scans the configured shares.
+ /// Scans the configured shares on the local host.
/// </summary>
/// <returns>The operation context.</returns>
/// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
@@ -84,7 +90,7 @@ namespace slskd.Shares
Task<(int Directories, int Files)> SummarizeShareAsync(Share share);
/// <summary>
- /// Cancels the currently running scan, if one is running.
+ /// Cancels the currently running scan on the local host, if one is running.
/// </summary>
/// <returns>A value indicating whether a scan was cancelled.</returns>
bool TryCancelScan();
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 file="ShareConnectionStringFactory.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Shares
+{
+ using System;
+
+ /// <summary>
+ /// Creates connection strings for share cache databases.
+ /// </summary>
+ public class ShareConnectionStringFactory
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ShareConnectionStringFactory"/> class.
+ /// </summary>
+ /// <param name="createFromFile">The function used to create a connection string for a share cache database.</param>
+ /// <param name="createFromMemory">The function used to create an in-memory connection string for a share cache database.</param>
+ /// <param name="createBackupFromFile">The function used to crate a connection string for a share cache backup database.</param>
+ public ShareConnectionStringFactory(
+ Func<string, string> createFromFile,
+ Func<string, string> createFromMemory,
+ Func<string, string> createBackupFromFile)
+ {
+ CreateFromFile = createFromFile;
+ CreateFromMemory = createFromMemory;
+ CreateBackupFromFile = createBackupFromFile;
+ }
+
+ /// <summary>
+ /// Gets a function used to create a connection string for a share cache database.
+ /// </summary>
+ public Func<string, string> CreateFromFile { get; }
+
+ /// <summary>
+ /// Gets a function used to create an in-memory connection string for a share cache database.
+ /// </summary>
+ public Func<string, string> CreateFromMemory { get; }
+
+ /// <summary>
+ /// Gets a function used to create a connection string for a share cache backup database.
+ /// </summary>
+ public Func<string, string> CreateBackupFromFile { get; }
+ }
+}
diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs
index 74f0d131..f5e7e52d 100644
--- a/src/slskd/Shares/ShareScanner.cs
+++ b/src/slskd/Shares/ShareScanner.cs
@@ -65,11 +65,14 @@ namespace slskd.Shares
/// </summary>
/// <param name="workerCount"></param>
/// <param name="soulseekFileFactory"></param>
- public ShareScanner(int workerCount, ISoulseekFileFactory soulseekFileFactory = null)
+ public ShareScanner(
+ int workerCount,
+ IReadWriteShareRepository shareRepository,
+ ISoulseekFileFactory soulseekFileFactory = null)
{
WorkerCount = workerCount;
SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory();
- Repository = new ShareRepository(Program.ConnectionStrings.Shares);
+ Repository = shareRepository;
}
/// <summary>
@@ -84,7 +87,7 @@ namespace slskd.Shares
private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>();
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1);
private CancellationTokenSource CancellationTokenSource { get; set; }
- private IShareRepository Repository { get; }
+ private IReadWriteShareRepository Repository { get; }
/// <summary>
/// Scans the configured shares and fills the cache.
@@ -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 098fa56c..12131eae 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;
@@ -38,16 +37,40 @@ namespace slskd.Shares
/// <summary>
/// Initializes a new instance of the <see cref="ShareService"/> class.
/// </summary>
+ /// <param name="shareConnectionStringFactory"></param>
/// <param name="optionsMonitor"></param>
/// <param name="scanner"></param>
public ShareService(
+ ShareConnectionStringFactory shareConnectionStringFactory,
IOptionsMonitor<Options> optionsMonitor,
IShareScanner scanner = null)
{
- CacheStorageMode = optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum<StorageMode>();
+ var options = optionsMonitor.CurrentValue;
+
+ ConnectionStringFactory = shareConnectionStringFactory;
+ CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum<StorageMode>();
+
+ if (CacheStorageMode == StorageMode.Memory)
+ {
+ ConnectionString = ConnectionStringFactory.CreateFromMemory(options.InstanceName);
+ }
+ else
+ {
+ ConnectionString = ConnectionStringFactory.CreateFromFile(options.InstanceName);
+ }
+
+ BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile(options.InstanceName);
+
+ var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online);
+ var repository = new SqliteShareRepository(ConnectionString);
+
+ Local = (host, repository);
+
+ AllRepositories = new List<IShareRepository>(new[] { repository });
Scanner = scanner ?? new ShareScanner(
- workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers);
+ shareRepository: repository,
+ workerCount: options.Shares.Cache.Workers);
Scanner.StateMonitor.OnChange(cacheState =>
{
@@ -67,8 +90,6 @@ namespace slskd.Shares
});
});
- Repository = new ShareRepository(connectionString: Program.ConnectionStrings.Shares);
-
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
@@ -78,24 +99,45 @@ namespace slskd.Shares
}
/// <summary>
- /// Gets the list of configured shares.
+ /// Gets the list of share hosts.
/// </summary>
- public IReadOnlyList<Share> Shares => SharesList.AsReadOnly();
+ public IReadOnlyList<Host> Hosts => HostDictionary.Values.Select(v => v.Host).Prepend(Local.Host).ToList().AsReadOnly();
/// <summary>
/// Gets the state monitor for the service.
/// </summary>
public IStateMonitor<ShareState> 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; }
private IOptionsMonitor<Options> OptionsMonitor { get; }
- private List<Share> SharesList { get; set; } = new List<Share>();
+ private ConcurrentDictionary<string, (Host Host, IShareRepository Repository)> HostDictionary { get; set; } = new();
private IManagedState<ShareState> State { get; } = new ManagedState<ShareState>();
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1);
private StorageMode CacheStorageMode { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<ShareService>();
+ private (Host Host, IReadWriteShareRepository Repository) Local { get; set; }
+ private IEnumerable<IShareRepository> AllRepositories { get; set; }
+
+ /// <summary>
+ /// Adds a new, or updates an existing, share host.
+ /// </summary>
+ /// <param name="host">The host to add or update.</param>
+ 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);
+ }
/// <summary>
/// Returns the entire contents of the share.
@@ -117,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 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 = Repository.ListFiles(prefix, includeFullPath: true);
+ var files = AllRepositories.SelectMany(r => r.ListFiles(prefix, includeFullPath: true));
var groups = files
.GroupBy(file => Path.GetDirectoryName(file.Filename))
@@ -158,7 +200,7 @@ namespace slskd.Shares
{
var localPath = directory.LocalizePath();
- var files = Repository.ListFiles(localPath);
+ var files = AllRepositories.SelectMany(r => r.ListFiles(localPath));
return Task.FromResult(new Directory(directory, files));
}
@@ -174,7 +216,9 @@ namespace slskd.Shares
/// </exception>
public Task<FileInfo> ResolveFileAsync(string remoteFilename)
{
- var resolvedFilename = Repository.FindFilename(remoteFilename.LocalizePath());
+ var resolvedFilename = AllRepositories
+ .Select(r => r.FindFilename(remoteFilename.LocalizePath()))
+ .FirstOrDefault(r => !string.IsNullOrEmpty(r));
if (string.IsNullOrEmpty(resolvedFilename))
{
@@ -200,7 +244,7 @@ namespace slskd.Shares
/// <returns>The matching files.</returns>
public Task<IEnumerable<File>> SearchAsync(SearchQuery query)
{
- var results = Repository.Search(query);
+ var results = AllRepositories.SelectMany(r => r.Search(query));
return Task.FromResult(results.Select(r => new File(
r.Code,
@@ -215,9 +259,13 @@ namespace slskd.Shares
/// </summary>
/// <returns>The operation context.</returns>
/// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
- public Task ScanAsync()
+ public async Task ScanAsync()
{
- return Scanner.ScanAsync(Shares, OptionsMonitor.CurrentValue.Shares);
+ await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares);
+
+ Log.Debug("Backing up shared file cache database...");
+ Local.Repository.BackupTo(BackupConnectionString);
+ Log.Debug("Shared file cache database backup complete");
}
/// <summary>
@@ -229,8 +277,8 @@ namespace slskd.Shares
{
var prefix = share.RemotePath + Path.DirectorySeparatorChar;
- var dirs = Repository.CountDirectories(prefix);
- var files = 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));
}
@@ -263,11 +311,11 @@ namespace slskd.Shares
{
Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup...");
- if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup))
+ if (Local.Repository.TryValidate(BackupConnectionString))
{
Log.Information("Share cache backup validated. Attempting to restore...");
- Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup);
+ Local.Repository.RestoreFrom(connectionString: BackupConnectionString);
Log.Information("Share cache successfully restored from backup");
}
@@ -281,7 +329,7 @@ namespace slskd.Shares
{
Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate...");
- if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares))
+ if (Local.Repository.TryValidate(ConnectionString))
{
// no-op
}
@@ -289,11 +337,11 @@ 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 (Local.Repository.TryValidate(BackupConnectionString))
{
Log.Information("Share cache backup validated. Attempting to restore...");
- Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup);
+ Local.Repository.RestoreFrom(connectionString: BackupConnectionString);
Log.Information("Share cache successfully restored from backup");
}
@@ -318,8 +366,8 @@ namespace slskd.Shares
Faulted = false,
Ready = true,
ScanProgress = 1,
- Directories = Repository.CountDirectories(),
- Files = Repository.CountFiles(),
+ Directories = Local.Repository.CountDirectories(),
+ Files = Local.Repository.CountFiles(),
});
}
catch (Exception ex)
@@ -359,9 +407,10 @@ namespace slskd.Shares
.OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent
.ToList();
- SharesList = shares;
+ Local = (Local.Host with { Shares = shares }, Local.Repository);
- State.SetValue(state => state with { ScanPending = true });
+ // todo: initialize agent hosts
+ // todo: don't destroy or overwrite existing hosts!
LastOptionsHash = optionsHash;
}
diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index 7b723ac6..28788c3f 100644
--- a/src/slskd/Shares/ShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -1,4 +1,4 @@
-// <copyright file="ShareRepository.cs" company="slskd Team">
+// <copyright file="SqliteShareRepository.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -28,150 +28,33 @@ namespace slskd.Shares
/// <summary>
/// Persistent storage of shared files and metadata.
/// </summary>
- public interface IShareRepository
+ public class SqliteShareRepository : IReadWriteShareRepository
{
/// <summary>
- /// Backs the current database up to the database at the specified <paramref name="connectionString"/>.
- /// </summary>
- /// <param name="connectionString">The connection string of the destination database.</param>
- void BackupTo(string connectionString);
-
- /// <summary>
- /// Counts the number of directories in the database.
- /// </summary>
- /// <param name="parentDirectory">The optional directory prefix used for counting subdirectories.</param>
- /// <returns>The number of directories.</returns>
- int CountDirectories(string parentDirectory = null);
-
- /// <summary>
- /// Counts the number of files in the database.
- /// </summary>
- /// <param name="parentDirectory">The optional directory prefix used for counting files in a subdirectory.</param>
- /// <returns>The number of files.</returns>
- int CountFiles(string parentDirectory = null);
-
- /// <summary>
- /// Creates a new database.
- /// </summary>
- /// <remarks>
- /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case
- /// tables are explicitly dropped prior to creation.
- /// </remarks>
- /// <param name="discardExisting">An optional value that determines whether the existing database should be discarded.</param>
- void Create(bool discardExisting = false);
-
- /// <summary>
- /// Finds the filename of the file matching the specified <paramref name="maskedFilename"/>.
- /// </summary>
- /// <param name="maskedFilename">The fully qualified remote path of the file.</param>
- /// <returns>The filename, if found.</returns>
- string FindFilename(string maskedFilename);
-
- /// <summary>
- /// Inserts a directory.
- /// </summary>
- /// <param name="name">The fully qualified local name of the directory.</param>
- /// <param name="timestamp">The timestamp to assign to the record.</param>
- void InsertDirectory(string name, long timestamp);
-
- /// <summary>
- /// Inserts a file.
- /// </summary>
- /// <param name="maskedFilename">The fully qualified remote path of the file.</param>
- /// <param name="originalFilename">The fully qualified local path of the file.</param>
- /// <param name="touchedAt">The timestamp at which the file was last modified, according to the host OS.</param>
- /// <param name="file">The Soulseek.File instance representing the file.</param>
- /// <param name="timestamp">The timestamp to assign to the record.</param>
- void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, Soulseek.File file, long timestamp);
-
- /// <summary>
- /// Inserts a scan record at the specified <paramref name="timestamp"/>.
- /// </summary>
- /// <param name="timestamp">The timestamp associated with the scan.</param>
- /// <param name="options">The options snapshot at the start of the scan.</param>
- void InsertScan(long timestamp, Options.SharesOptions options);
-
- /// <summary>
- /// Lists all directories.
- /// </summary>
- /// <param name="parentDirectory">The optional directory prefix used for listing subdirectories.</param>
- /// <returns>The list of directories.</returns>
- IEnumerable<string> ListDirectories(string parentDirectory = null);
-
- /// <summary>
- /// Lists all files.
- /// </summary>
- /// <param name="parentDirectory">The optional parent directory.</param>
- /// <param name="includeFullPath">A value indicating whether the fully qualified path should be returned.</param>
- /// <returns>The list of files.</returns>
- IEnumerable<Soulseek.File> ListFiles(string parentDirectory = null, bool includeFullPath = false);
-
- /// <summary>
- /// Deletes directory records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>.
- /// </summary>
- /// <param name="olderThanTimestamp">The timestamp before which to delete directories.</param>
- /// <returns>The number of records deleted.</returns>
- long PruneDirectories(long olderThanTimestamp);
-
- /// <summary>
- /// Deletes file records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>.
- /// </summary>
- /// <param name="olderThanTimestamp">The timestamp before which to delete files.</param>
- /// <returns>The number of records deleted.</returns>
- long PruneFiles(long olderThanTimestamp);
-
- /// <summary>
- /// Restores the current database from the database at the specified <paramref name="connectionString"/>.
- /// </summary>
- /// <param name="connectionString">The connection string of the source database.</param>
- void RestoreFrom(string connectionString);
-
- /// <summary>
- /// Searches the database for files matching the specified <paramref name="query"/>.
- /// </summary>
- /// <param name="query">The search query.</param>
- /// <returns>The list of matching files.</returns>
- IEnumerable<Soulseek.File> Search(SearchQuery query);
-
- /// <summary>
- /// Updates the scan started at the specified <paramref name="timestamp"/> to set the <paramref name="end"/>.
- /// </summary>
- /// <param name="timestamp">The timestamp associated with the scan.</param>
- /// <param name="end">The timestamp at the conclusion of the scan.</param>
- void UpdateScan(long timestamp, long end);
- }
-
- /// <summary>
- /// Persistent storage of shared files and metadata.
- /// </summary>
- public class ShareRepository : IShareRepository
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ShareRepository"/> class.
+ /// Initializes a new instance of the <see cref="SqliteShareRepository"/> class.
/// </summary>
/// <param name="connectionString"></param>
- public ShareRepository(string connectionString)
+ public SqliteShareRepository(string connectionString)
{
ConnectionString = connectionString;
}
- private string ConnectionString { get; }
- private ILogger Log { get; } = Serilog.Log.ForContext<ShareRepository>();
+ /// <summary>
+ /// Gets the connection string for this repository.
+ /// </summary>
+ public string ConnectionString { get; }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<SqliteShareRepository>();
/// <summary>
- /// Attempts to validate the database at the specified <paramref name="connectionString"/>.
+ /// Attempts to validate the database at the specified <paramref name="connectionString"/>, or the
+ /// default <see cref="ConnectionString"/>.
/// </summary>
/// <param name="connectionString">The connection string of the database to validate.</param>
/// <returns>A value indicating whether the database is valid.</returns>
- /// <exception cref="ArgumentNullException">Thrown if no connection string is provided.</exception>
- 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<ShareRepository>();
+ 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'
@@ -190,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();
@@ -213,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);
}
}
@@ -229,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;
}
}
@@ -274,7 +157,7 @@ namespace slskd.Shares
}
finally
{
- cmd.Dispose();
+ cmd?.Dispose();
}
}
@@ -307,7 +190,7 @@ namespace slskd.Shares
}
finally
{
- cmd.Dispose();
+ cmd?.Dispose();
}
}
@@ -346,7 +229,7 @@ namespace slskd.Shares
/// </summary>
/// <param name="maskedFilename">The fully qualified remote path of the file.</param>
/// <returns>The filename, if found.</returns>
- 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);
@@ -466,7 +349,7 @@ namespace slskd.Shares
}
finally
{
- cmd.Dispose();
+ cmd?.Dispose();
}
}
@@ -591,13 +474,12 @@ namespace slskd.Shares
"ORDER BY filenames.maskedFilename ASC;";
var results = new List<Soulseek.File>();
- SqliteDataReader reader = default;
try
{
using var conn = GetConnection();
using var cmd = new SqliteCommand(sql, conn);
- reader = cmd.ExecuteReader();
+ using var reader = cmd.ExecuteReader();
while (reader.Read())
{
diff --git a/src/slskd/Shares/Types/Host.cs b/src/slskd/Shares/Types/Host.cs
new file mode 100644
index 00000000..3c5c9f9f
--- /dev/null
+++ b/src/slskd/Shares/Types/Host.cs
@@ -0,0 +1,64 @@
+// <copyright file="Host.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Shares
+{
+ using System.Collections.Generic;
+ using System.Linq;
+
+ /// <summary>
+ /// A share host.
+ /// </summary>
+ public record Host
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Host"/> class.
+ /// </summary>
+ /// <param name="name">The name of the host.</param>
+ /// <param name="type">The type of the host.</param>
+ /// <param name="shares">The collection of hosted shares.</param>
+ /// <param name="state">The initial state of the host.</param>
+ public Host(string name, HostType type, IEnumerable<Share> shares = null, HostState state = HostState.Offline)
+ {
+ Name = name;
+ Type = type;
+ Shares = shares ?? Enumerable.Empty<Share>();
+ State = state;
+ }
+
+ /// <summary>
+ /// Gets the name of the host.
+ /// </summary>
+ /// <remarks>Corresponds to the configured <see cref="Options.InstanceName"/> of the host.</remarks>
+ public string Name { get; }
+
+ /// <summary>
+ /// Gets the collection of hosted shares.
+ /// </summary>
+ public IEnumerable<Share> Shares { get; init; }
+
+ /// <summary>
+ /// Gets the host state.
+ /// </summary>
+ public HostState State { get; init; }
+
+ /// <summary>
+ /// Gets the host type.
+ /// </summary>
+ public HostType Type { get; }
+ }
+} \ 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 file="HostState.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Shares
+{
+ /// <summary>
+ /// The state of a share host.
+ /// </summary>
+ public enum HostState
+ {
+ /// <summary>
+ /// Offline; unable to service requests.
+ /// </summary>
+ Offline = 0,
+
+ /// <summary>
+ /// Online; able to service requests.
+ /// </summary>
+ Online = 1,
+ }
+}
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 file="HostType.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Shares
+{
+ /// <summary>
+ /// The type of host.
+ /// </summary>
+ public enum HostType
+ {
+ /// <summary>
+ /// Local.
+ /// </summary>
+ Local = 0,
+
+ /// <summary>
+ /// Remote; shares are hosted by an Agent.
+ /// </summary>
+ Remote = 1,
+ }
+}