diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-10-14 18:29:11 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2022-10-14 18:29:11 -0500 |
| commit | a0a984cebed195a814152de95bed480ea9a3d29d (patch) | |
| tree | 4320d179d24aae7a96fe055ea1fb43f6bca0fdf5 /src | |
| parent | 4d69426a19ffff519368ec2b75e8634fdd23d861 (diff) | |
| download | slskd-a0a984cebed195a814152de95bed480ea9a3d29d.tar.gz | |
wip
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Network/API/Controllers/NetworkController.cs | 25 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkClient.cs | 28 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Shares/IReadOnlyShareRepository.cs | 26 | ||||
| -rw-r--r-- | src/slskd/Shares/IReadWriteShareRepository.cs | 96 | ||||
| -rw-r--r-- | src/slskd/Shares/IShareRepository.cs | 89 | ||||
| -rw-r--r-- | src/slskd/Shares/IShareRepositoryFactory.cs | 46 | ||||
| -rw-r--r-- | src/slskd/Shares/IShareService.cs | 13 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareConnectionStringFactory.cs | 58 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareRepositoryFactory.cs | 74 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareScanner.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareService.cs | 64 | ||||
| -rw-r--r-- | src/slskd/Shares/SqliteShareRepository.cs | 183 |
13 files changed, 384 insertions, 327 deletions
diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 69e3d789..deeddc04 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -24,6 +24,7 @@ namespace slskd.Network using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Serilog; + using slskd.Shares; /// <summary> /// Network. @@ -33,11 +34,19 @@ namespace slskd.Network [ApiController] public class NetworkController : ControllerBase { - public NetworkController(INetworkService networkService) + public NetworkController( + INetworkService networkService, + IShareService shareService, + IShareRepositoryFactory shareRepositoryFactory) { Network = networkService; + Shares = shareService; + + ShareRepositoryFactory = shareRepositoryFactory; } + private IShareRepositoryFactory ShareRepositoryFactory { get; } + private IShareService Shares { get; } private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext<NetworkController>(); @@ -114,14 +123,22 @@ namespace slskd.Network Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); - using var inputStream = Request.Form.Files.First().OpenReadStream(); + using var inputStream = Request.Form.Files[0].OpenReadStream(); await inputStream.CopyToAsync(outputStream); Log.Debug("Upload of share from {Agent} to {Filename} complete", agent, temp); - // todo: validate database - // todo: add contents of db to local db + var repository = ShareRepositoryFactory.CreateFromFile(temp); + + if (!repository.TryValidate(out var problems)) + { + return BadRequest(string.Join(", ", problems)); + } + + var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); + + destinationRepository.RestoreFrom(repository); return Ok(); } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 10e33118..15f114f9 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -127,7 +127,7 @@ namespace slskd.Network Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); Log.Debug("Backing up shares to {Filename}", temp); - Shares.BackupTo($"Data Source={temp};Pooling=False;"); // quite a leaky abstraction + await Shares.DumpAsync(temp); Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); @@ -136,18 +136,22 @@ namespace slskd.Network FileStream stream = default; - try - { - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - } - catch (Exception ex) + while (true) { - // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling - // Pooling=False should be included in the connection string and this shouldn't be an issue, but - // since i don't totally understand the behavior, i'll leave this for now. - Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); - SqliteConnection.ClearAllPools(); - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + try + { + stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + break; + } + catch (Exception ex) + { + // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling + // Pooling=False should be included in the connection string and this shouldn't be an issue, but + // since i don't totally understand the behavior, i'll leave this for now. + Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); + SqliteConnection.ClearAllPools(); + await Task.Delay(100); + } } using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c5d0f961..b9d43992 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -528,10 +528,7 @@ namespace slskd 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.AddTransient<IShareRepositoryFactory, SqliteShareRepositoryFactory>(); services.AddSingleton<ISearchService, SearchService>(); services.AddSingleton<IUserService, UserService>(); diff --git a/src/slskd/Shares/IReadOnlyShareRepository.cs b/src/slskd/Shares/IReadOnlyShareRepository.cs deleted file mode 100644 index fff587ad..00000000 --- a/src/slskd/Shares/IReadOnlyShareRepository.cs +++ /dev/null @@ -1,26 +0,0 @@ -// <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 -// 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> - /// Read-only persistent storage of shared files and metadata. - /// </summary> - public interface IReadOnlyShareRepository : IShareRepository - { - } -} diff --git a/src/slskd/Shares/IReadWriteShareRepository.cs b/src/slskd/Shares/IReadWriteShareRepository.cs deleted file mode 100644 index c6701753..00000000 --- a/src/slskd/Shares/IReadWriteShareRepository.cs +++ /dev/null @@ -1,96 +0,0 @@ -// <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 index 87c2c386..0cf5cd80 100644 --- a/src/slskd/Shares/IShareRepository.cs +++ b/src/slskd/Shares/IShareRepository.cs @@ -17,6 +17,7 @@ namespace slskd.Shares { + using System; using System.Collections.Generic; using Soulseek; @@ -31,6 +32,12 @@ namespace slskd.Shares string ConnectionString { get; } /// <summary> + /// Backs the current database up to the database at the specified <paramref name="repository"/>. + /// </summary> + /// <param name="repository">The destination repository.</param> + void BackupTo(IShareRepository repository); + + /// <summary> /// Counts the number of directories in the database. /// </summary> /// <param name="parentDirectory">The optional directory prefix used for counting subdirectories.</param> @@ -45,6 +52,22 @@ namespace slskd.Shares 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> + /// Dumps the contents of the database to a file. + /// </summary> + /// <param name="filename">The destination file.</param> + void DumpTo(string filename); + + /// <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> @@ -52,6 +75,30 @@ namespace slskd.Shares 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, 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> @@ -67,6 +114,26 @@ namespace slskd.Shares IEnumerable<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="repository"/>. + /// </summary> + /// <param name="repository">The destination repository.</param> + void RestoreFrom(IShareRepository repository); + + /// <summary> /// Searches the database for files matching the specified <paramref name="query"/>. /// </summary> /// <param name="query">The search query.</param> @@ -74,11 +141,23 @@ namespace slskd.Shares IEnumerable<File> Search(SearchQuery query); /// <summary> - /// Attempts to validate the database at the specified <paramref name="connectionString"/>, or the - /// default <see cref="ConnectionString"/>. + /// Attempts to validate the backing database. + /// </summary> + /// <returns>A value indicating whether the database is valid.</returns> + bool TryValidate(); + + /// <summary> + /// Attempts to validate the backing database. /// </summary> - /// <param name="connectionString">The connection string of the database to validate.</param> + /// <param name="problems">The list of problems, if the database is invalid.</param> /// <returns>A value indicating whether the database is valid.</returns> - bool TryValidate(string connectionString = null); + bool TryValidate(out IEnumerable<string> problems); + + /// <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/IShareRepositoryFactory.cs b/src/slskd/Shares/IShareRepositoryFactory.cs new file mode 100644 index 00000000..a43f84d9 --- /dev/null +++ b/src/slskd/Shares/IShareRepositoryFactory.cs @@ -0,0 +1,46 @@ +// <copyright file="IShareRepositoryFactory.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> + /// Persistent storage of a shared file cache. + /// </summary> + public interface IShareRepositoryFactory + { + /// <summary> + /// Create a repository for the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the agent.</param> + /// <returns>The created repository.</returns> + IShareRepository CreateFromHost(string name); + + /// <summary> + /// Create a repository backup for the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the agent.</param> + /// <returns>The created repository.</returns> + IShareRepository CreateFromHostBackup(string name); + + /// <summary> + /// Create a repository for the specified <paramref name="filename"/>. + /// </summary> + /// <param name="filename">The fully qualified path of the filename.</param> + /// <returns>The created repository.</returns> + IShareRepository CreateFromFile(string filename); + } +} diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 90fa115d..b55db482 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -43,18 +43,19 @@ namespace slskd.Shares void AddOrUpdateHost(Host host); /// <summary> - /// Backs contents of the cache up to the specified file. - /// </summary> - /// <param name="connectionString">The destination connection string.</param> - void BackupTo(string connectionString); - - /// <summary> /// Returns the entire contents of the share. /// </summary> /// <returns>The entire contents of the share.</returns> Task<IEnumerable<Directory>> BrowseAsync(Share share = null); /// <summary> + /// Dumps the local share cache to a file. + /// </summary> + /// <param name="filename">The destination file.</param> + /// <returns>The operation context.</returns> + Task DumpAsync(string filename); + + /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. /// </summary> /// <param name="directory">The directory for which the contents are to be listed.</param> diff --git a/src/slskd/Shares/ShareConnectionStringFactory.cs b/src/slskd/Shares/ShareConnectionStringFactory.cs deleted file mode 100644 index d9b7492b..00000000 --- a/src/slskd/Shares/ShareConnectionStringFactory.cs +++ /dev/null @@ -1,58 +0,0 @@ -// <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/ShareRepositoryFactory.cs b/src/slskd/Shares/ShareRepositoryFactory.cs new file mode 100644 index 00000000..fc58c397 --- /dev/null +++ b/src/slskd/Shares/ShareRepositoryFactory.cs @@ -0,0 +1,74 @@ +// <copyright file="ShareRepositoryFactory.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> + +using System.IO; + +namespace slskd.Shares +{ + /// <summary> + /// Persistent storage of a shared file cache. + /// </summary> + public class SqliteShareRepositoryFactory : IShareRepositoryFactory + { + /// <summary> + /// Initializes a new instance of the <see cref="SqliteShareRepositoryFactory"/> class. + /// </summary> + /// <param name="optionsAtStartup"></param> + public SqliteShareRepositoryFactory( + OptionsAtStartup optionsAtStartup) + { + StorageMode = optionsAtStartup.Shares.Cache.StorageMode.ToEnum<StorageMode>(); + } + + private StorageMode StorageMode { get; } + + /// <summary> + /// Create a repository for the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the agent.</param> + /// <returns>The created repository.</returns> + public IShareRepository CreateFromHost(string name) + { + if (StorageMode == StorageMode.Memory) + { + return new SqliteShareRepository($"Data Source=file:shares.{name}?mode=memory;Cache=shared"); + } + + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.db"); + return new SqliteShareRepository($"Data Source={file};Cache=shared"); + } + + /// <summary> + /// Create a repository backup for the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the agent.</param> + /// <returns>The created repository.</returns> + public IShareRepository CreateFromHostBackup(string name) + { + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.bak.db"); + return new SqliteShareRepository($"Data Source={file}"); + } + + /// <summary> + /// Create a repository for the specified <paramref name="filename"/>. + /// </summary> + /// <param name="filename">The fully qualified path of the filename.</param> + /// <returns>The created repository.</returns> + public IShareRepository CreateFromFile(string filename) + => new SqliteShareRepository($"Data Source={filename}"); + } +} diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index f5e7e52d..7a174396 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -67,7 +67,7 @@ namespace slskd.Shares /// <param name="soulseekFileFactory"></param> public ShareScanner( int workerCount, - IReadWriteShareRepository shareRepository, + IShareRepository shareRepository, ISoulseekFileFactory soulseekFileFactory = null) { WorkerCount = workerCount; @@ -87,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 IReadWriteShareRepository Repository { get; } + private IShareRepository Repository { get; } /// <summary> /// Scans the configured shares and fills the cache. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index a0aec286..cc35477e 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -37,32 +37,22 @@ namespace slskd.Shares /// <summary> /// Initializes a new instance of the <see cref="ShareService"/> class. /// </summary> - /// <param name="shareConnectionStringFactory"></param> + /// <param name="shareRepositoryFactory"></param> /// <param name="optionsMonitor"></param> /// <param name="scanner"></param> public ShareService( - ShareConnectionStringFactory shareConnectionStringFactory, + IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor<Options> optionsMonitor, IShareScanner scanner = null) { 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); + ShareRepositoryFactory = shareRepositoryFactory; var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online); - var repository = new SqliteShareRepository(ConnectionString); + var repository = ShareRepositoryFactory.CreateFromHost(options.InstanceName); Local = (host, repository); @@ -108,9 +98,7 @@ namespace slskd.Shares /// </summary> public IStateMonitor<ShareState> StateMonitor { get; } - private string ConnectionString { get; } - private string BackupConnectionString { get; } - private ShareConnectionStringFactory ConnectionStringFactory { get; } + private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareScanner Scanner { get; } private string LastOptionsHash { get; set; } private IOptionsMonitor<Options> OptionsMonitor { get; } @@ -119,7 +107,7 @@ namespace slskd.Shares 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 (Host Host, IShareRepository Repository) Local { get; set; } private IEnumerable<IShareRepository> AllRepositories { get; set; } /// <summary> @@ -128,9 +116,11 @@ namespace slskd.Shares /// <param name="host">The host to add or update.</param> public void AddOrUpdateHost(Host host) { + // we assume that if this method is called that the caller has verified that the + // file for the host exists and is valid. HostDictionary.AddOrUpdate( key: host.Name, - addValueFactory: (key) => (host, new SqliteShareRepository(ConnectionStringFactory.CreateFromFile(host.Name))), + addValueFactory: (key) => (host, ShareRepositoryFactory.CreateFromHost(host.Name)), updateValueFactory: (_, existing) => (host, existing.Repository)); AllRepositories = HostDictionary.Values @@ -140,15 +130,6 @@ namespace slskd.Shares } /// <summary> - /// Backs contents of the cache up to the specified file. - /// </summary> - /// <param name="connectionString">The destination connection string.</param> - public void BackupTo(string connectionString) - { - Repository.BackupTo(connectionString); - } - - /// <summary> /// Returns the entire contents of the share. /// </summary> /// <returns>The entire contents of the share.</returns> @@ -201,6 +182,17 @@ namespace slskd.Shares } /// <summary> + /// Dumps the local share cache to a file. + /// </summary> + /// <param name="filename">The destination file.</param> + /// <returns>The operation context.</returns> + public Task DumpAsync(string filename) + { + Local.Repository.DumpTo(filename); + return Task.CompletedTask; + } + + /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. /// </summary> /// <param name="directory">The directory for which the contents are to be listed.</param> @@ -272,7 +264,7 @@ namespace slskd.Shares await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares); Log.Debug("Backing up shared file cache database..."); - Local.Repository.BackupTo(BackupConnectionString); + Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName)); Log.Debug("Shared file cache database backup complete"); } @@ -319,11 +311,13 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (Local.Repository.TryValidate(BackupConnectionString)) + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + + if (backupRepository.TryValidate(out _)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Local.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(backupRepository); Log.Information("Share cache successfully restored from backup"); } @@ -337,7 +331,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (Local.Repository.TryValidate(ConnectionString)) + if (Local.Repository.TryValidate(out _)) { // no-op } @@ -345,11 +339,13 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (Local.Repository.TryValidate(BackupConnectionString)) + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + + if (backupRepository.TryValidate(out _)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Local.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(backupRepository); Log.Information("Share cache successfully restored from backup"); } diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 28788c3f..9b65794e 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -28,7 +28,7 @@ namespace slskd.Shares /// <summary> /// Persistent storage of shared files and metadata. /// </summary> - public class SqliteShareRepository : IReadWriteShareRepository + public class SqliteShareRepository : IShareRepository { /// <summary> /// Initializes a new instance of the <see cref="SqliteShareRepository"/> class. @@ -47,84 +47,13 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext<SqliteShareRepository>(); /// <summary> - /// Attempts to validate the database at the specified <paramref name="connectionString"/>, or the - /// default <see cref="ConnectionString"/>. + /// Backs the current database up to the database at the specified <paramref name="repository"/>. /// </summary> - /// <param name="connectionString">The connection string of the database to validate.</param> - /// <returns>A value indicating whether the database is valid.</returns> - public bool TryValidate(string connectionString = null) - { - 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' - var schema = new Dictionary<string, string>() - { - { "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; - } - } - - /// <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> - public void BackupTo(string connectionString) + /// <param name="repository">The destination repository.</param> + public void BackupTo(IShareRepository repository) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(connectionString); + using var backupConn = GetConnection(repository.ConnectionString); sourceConn.BackupDatabase(backupConn); } @@ -225,6 +154,19 @@ namespace slskd.Shares } /// <summary> + /// Dumps the contents of the database to a file. + /// </summary> + /// <param name="filename">The destination file.</param> + public void DumpTo(string filename) + { + using var sourceConn = GetConnection(ConnectionString); + using var backupConn = GetConnection($"Data Source={filename}"); + sourceConn.BackupDatabase(backupConn); + + Sqlite. + } + + /// <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> @@ -442,12 +384,12 @@ namespace slskd.Shares } /// <summary> - /// Restores the current database from the database at the specified <paramref name="connectionString"/>. + /// Restores the current database from the database at the specified <paramref name="repository"/>. /// </summary> - /// <param name="connectionString">The connection string of the source database.</param> - public void RestoreFrom(string connectionString) + /// <param name="repository">The destination repository.</param> + public void RestoreFrom(IShareRepository repository) { - using var sourceConn = GetConnection(connectionString); + using var sourceConn = GetConnection(repository.ConnectionString); using var restoreConn = GetConnection(); sourceConn.BackupDatabase(restoreConn); } @@ -505,6 +447,87 @@ namespace slskd.Shares } /// <summary> + /// Attempts to validate the backing database. + /// </summary> + /// <returns>A value indicating whether the database is valid.</returns> + public bool TryValidate() + { + return TryValidate(out _); + } + + /// <summary> + /// Attempts to validate the backing database. + /// </summary> + /// <param name="problems">The list of problems, if the database is invalid.</param> + /// <returns>A value indicating whether the database is valid.</returns> + public bool TryValidate(out IEnumerable<string> problems) + { + var list = new List<string>(); + problems = list; + + // 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<string, string>() + { + { "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) + { + list.Add($"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) + { + list.Add($"Expected {schema.Count} tables, found {rows}"); + } + + return !problems.Any(); + } + catch (Exception ex) + { + Log.Debug(ex, $"Failed to validate database: {ex.Message}"); + list.Add($"Failed to validate database: {ex.Message}"); + return false; + } + } + + /// <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> |
