From a0a984cebed195a814152de95bed480ea9a3d29d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 14 Oct 2022 18:29:11 -0500 Subject: wip --- .../Network/API/Controllers/NetworkController.cs | 25 ++- src/slskd/Network/NetworkClient.cs | 28 ++-- src/slskd/Program.cs | 5 +- src/slskd/Shares/IReadOnlyShareRepository.cs | 26 --- src/slskd/Shares/IReadWriteShareRepository.cs | 96 ----------- src/slskd/Shares/IShareRepository.cs | 89 +++++++++- src/slskd/Shares/IShareRepositoryFactory.cs | 46 ++++++ src/slskd/Shares/IShareService.cs | 13 +- src/slskd/Shares/ShareConnectionStringFactory.cs | 58 ------- src/slskd/Shares/ShareRepositoryFactory.cs | 74 +++++++++ src/slskd/Shares/ShareScanner.cs | 4 +- src/slskd/Shares/ShareService.cs | 64 ++++--- src/slskd/Shares/SqliteShareRepository.cs | 183 ++++++++++++--------- 13 files changed, 384 insertions(+), 327 deletions(-) delete mode 100644 src/slskd/Shares/IReadOnlyShareRepository.cs delete mode 100644 src/slskd/Shares/IReadWriteShareRepository.cs create mode 100644 src/slskd/Shares/IShareRepositoryFactory.cs delete mode 100644 src/slskd/Shares/ShareConnectionStringFactory.cs create mode 100644 src/slskd/Shares/ShareRepositoryFactory.cs (limited to 'src') 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; /// /// 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(); @@ -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(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(); - 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(); services.AddSingleton(); services.AddSingleton(); 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 (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 -{ - /// - /// Read-only persistent storage of shared files and metadata. - /// - 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 (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 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; @@ -30,6 +31,12 @@ namespace slskd.Shares /// string ConnectionString { get; } + /// + /// Backs the current database up to the database at the specified . + /// + /// The destination repository. + void BackupTo(IShareRepository repository); + /// /// Counts the number of directories in the database. /// @@ -44,6 +51,22 @@ namespace slskd.Shares /// The number of files. int CountFiles(string parentDirectory = null); + /// + /// 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); + + /// + /// Dumps the contents of the database to a file. + /// + /// The destination file. + void DumpTo(string filename); + /// /// Finds the filename of the file matching the specified . /// @@ -51,6 +74,30 @@ namespace slskd.Shares /// The filename, if found. string FindFilename(string maskedFilename); + /// + /// 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); + /// /// Lists all directories. /// @@ -66,6 +113,26 @@ namespace slskd.Shares /// The list of files. IEnumerable ListFiles(string parentDirectory = null, bool includeFullPath = false); + /// + /// 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); + + /// + /// Restores the current database from the database at the specified . + /// + /// The destination repository. + void RestoreFrom(IShareRepository repository); + /// /// Searches the database for files matching the specified . /// @@ -74,11 +141,23 @@ namespace slskd.Shares IEnumerable Search(SearchQuery query); /// - /// Attempts to validate the database at the specified , or the - /// default . + /// Attempts to validate the backing database. + /// + /// A value indicating whether the database is valid. + bool TryValidate(); + + /// + /// Attempts to validate the backing database. /// - /// The connection string of the database to validate. + /// The list of problems, if the database is invalid. /// A value indicating whether the database is valid. - bool TryValidate(string connectionString = null); + bool TryValidate(out IEnumerable problems); + + /// + /// 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/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 (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 +{ + /// + /// Persistent storage of a shared file cache. + /// + public interface IShareRepositoryFactory + { + /// + /// Create a repository for the specified . + /// + /// The name of the agent. + /// The created repository. + IShareRepository CreateFromHost(string name); + + /// + /// Create a repository backup for the specified . + /// + /// The name of the agent. + /// The created repository. + IShareRepository CreateFromHostBackup(string name); + + /// + /// Create a repository for the specified . + /// + /// The fully qualified path of the filename. + /// The created repository. + 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 @@ -42,18 +42,19 @@ namespace slskd.Shares /// The host to add or update. void AddOrUpdateHost(Host host); - /// - /// Backs contents of the cache up to the specified file. - /// - /// The destination connection string. - void BackupTo(string connectionString); - /// /// Returns the entire contents of the share. /// /// The entire contents of the share. Task> BrowseAsync(Share share = null); + /// + /// Dumps the local share cache to a file. + /// + /// The destination file. + /// The operation context. + Task DumpAsync(string filename); + /// /// Returns the contents of the specified . /// 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 (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - using System; - - /// - /// Creates connection strings for share cache databases. - /// - public class ShareConnectionStringFactory - { - /// - /// Initializes a new instance of the class. - /// - /// The function used to create a connection string for a share cache database. - /// The function used to create an in-memory connection string for a share cache database. - /// The function used to crate a connection string for a share cache backup database. - public ShareConnectionStringFactory( - Func createFromFile, - Func createFromMemory, - Func createBackupFromFile) - { - CreateFromFile = createFromFile; - CreateFromMemory = createFromMemory; - CreateBackupFromFile = createBackupFromFile; - } - - /// - /// Gets a function used to create a connection string for a share cache database. - /// - public Func CreateFromFile { get; } - - /// - /// Gets a function used to create an in-memory connection string for a share cache database. - /// - public Func CreateFromMemory { get; } - - /// - /// Gets a function used to create a connection string for a share cache backup database. - /// - public Func CreateBackupFromFile { get; } - } -} 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 (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/. +// + +using System.IO; + +namespace slskd.Shares +{ + /// + /// Persistent storage of a shared file cache. + /// + public class SqliteShareRepositoryFactory : IShareRepositoryFactory + { + /// + /// Initializes a new instance of the class. + /// + /// + public SqliteShareRepositoryFactory( + OptionsAtStartup optionsAtStartup) + { + StorageMode = optionsAtStartup.Shares.Cache.StorageMode.ToEnum(); + } + + private StorageMode StorageMode { get; } + + /// + /// Create a repository for the specified . + /// + /// The name of the agent. + /// The created repository. + 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"); + } + + /// + /// Create a repository backup for the specified . + /// + /// The name of the agent. + /// The created repository. + public IShareRepository CreateFromHostBackup(string name) + { + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.bak.db"); + return new SqliteShareRepository($"Data Source={file}"); + } + + /// + /// Create a repository for the specified . + /// + /// The fully qualified path of the filename. + /// The created repository. + 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 /// public ShareScanner( int workerCount, - IReadWriteShareRepository shareRepository, + IShareRepository 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 IReadWriteShareRepository Repository { get; } + private IShareRepository 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 a0aec286..cc35477e 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -37,32 +37,22 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// - /// + /// /// /// public ShareService( - ShareConnectionStringFactory shareConnectionStringFactory, + IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor optionsMonitor, IShareScanner scanner = null) { var options = optionsMonitor.CurrentValue; - ConnectionStringFactory = shareConnectionStringFactory; CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum(); - 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 /// public IStateMonitor 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 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(); - private (Host Host, IReadWriteShareRepository Repository) Local { get; set; } + private (Host Host, IShareRepository Repository) Local { get; set; } private IEnumerable AllRepositories { get; set; } /// @@ -128,9 +116,11 @@ namespace slskd.Shares /// The host to add or update. 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 @@ -139,15 +129,6 @@ namespace slskd.Shares .Prepend(Local.Repository); } - /// - /// Backs contents of the cache up to the specified file. - /// - /// The destination connection string. - public void BackupTo(string connectionString) - { - Repository.BackupTo(connectionString); - } - /// /// Returns the entire contents of the share. /// @@ -200,6 +181,17 @@ namespace slskd.Shares return Task.FromResult(results); } + /// + /// Dumps the local share cache to a file. + /// + /// The destination file. + /// The operation context. + public Task DumpAsync(string filename) + { + Local.Repository.DumpTo(filename); + return Task.CompletedTask; + } + /// /// Returns the contents of the specified . /// @@ -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 /// /// Persistent storage of shared files and metadata. /// - public class SqliteShareRepository : IReadWriteShareRepository + public class SqliteShareRepository : IShareRepository { /// /// Initializes a new instance of the class. @@ -47,84 +47,13 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Attempts to validate the database at the specified , or the - /// default . + /// Backs the current database up to the database at the specified . /// - /// The connection string of the database to validate. - /// A value indicating whether the database is valid. - 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() - { - { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, - { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, - { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, - { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, - { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, - { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, - { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, - { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, - { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, - }; - - try - { - Log.Debug("Validating shares database with connection string {String}", connectionString); - - using var conn = new SqliteConnection(connectionString); - conn.Open(); - - using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn); - - var reader = cmd.ExecuteReader(); - var rows = 0; - - while (reader.Read()) - { - var table = reader.GetString(0); - var expectedSql = reader.GetString(1); - - if (schema.TryGetValue(table, out var actualSql)) - { - if (actualSql != expectedSql) - { - throw new MissingFieldException($"Expected {table} schema to be {expectedSql}, found {actualSql}"); - } - else - { - Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); - } - } - - rows++; - } - - if (rows != schema.Count) - { - throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}"); - } - - return true; - } - catch (Exception ex) - { - Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); - return false; - } - } - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - public void BackupTo(string connectionString) + /// The destination repository. + public void BackupTo(IShareRepository repository) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(connectionString); + using var backupConn = GetConnection(repository.ConnectionString); sourceConn.BackupDatabase(backupConn); } @@ -224,6 +153,19 @@ namespace slskd.Shares "extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL);"); } + /// + /// Dumps the contents of the database to a file. + /// + /// The destination file. + public void DumpTo(string filename) + { + using var sourceConn = GetConnection(ConnectionString); + using var backupConn = GetConnection($"Data Source={filename}"); + sourceConn.BackupDatabase(backupConn); + + Sqlite. + } + /// /// Finds the filename of the file matching the specified . /// @@ -442,12 +384,12 @@ namespace slskd.Shares } /// - /// Restores the current database from the database at the specified . + /// Restores the current database from the database at the specified . /// - /// The connection string of the source database. - public void RestoreFrom(string connectionString) + /// The destination repository. + public void RestoreFrom(IShareRepository repository) { - using var sourceConn = GetConnection(connectionString); + using var sourceConn = GetConnection(repository.ConnectionString); using var restoreConn = GetConnection(); sourceConn.BackupDatabase(restoreConn); } @@ -504,6 +446,87 @@ namespace slskd.Shares } } + /// + /// Attempts to validate the backing database. + /// + /// A value indicating whether the database is valid. + public bool TryValidate() + { + return TryValidate(out _); + } + + /// + /// Attempts to validate the backing database. + /// + /// The list of problems, if the database is invalid. + /// A value indicating whether the database is valid. + public bool TryValidate(out IEnumerable problems) + { + var list = new List(); + 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() + { + { "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; + } + } + /// /// Updates the scan started at the specified to set the . /// -- cgit v1.2.3