From 97d1aa0bf26ed58a095420437595bdee7ea40f4c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 31 Aug 2022 16:55:13 -0500 Subject: use a record and read-only where possible --- src/slskd/Transfers/Types/UploadGroup.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs index 5696b0f1..22a98ae7 100644 --- a/src/slskd/Transfers/Types/UploadGroup.cs +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -17,13 +17,13 @@ namespace slskd.Transfers { - public sealed class UploadGroup + public sealed record UploadGroup { - public string Name { get; set; } - public int Priority { get; set; } + public string Name { get; init; } + public int Priority { get; init; } public bool SlotAvailable => UsedSlots < Slots; - public int Slots { get; set; } - public QueueStrategy Strategy { get; set; } + public int Slots { get; init; } + public QueueStrategy Strategy { get; init; } public int UsedSlots { get; set; } } } -- cgit v1.2.3 From bcc489ef42b9a17a3c2d6b52abe98792d9d39558 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 31 Aug 2022 16:56:29 -0500 Subject: expose GlobalSlots --- src/slskd/Transfers/Uploads/UploadQueue.cs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 36e5474c..0ab10a7e 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -34,6 +34,11 @@ namespace slskd.Transfers /// public interface IUploadQueue { + /// + /// Gets the global upload slot limit. + /// + int GlobalSlots { get; } + /// /// Awaits the start of an upload. /// @@ -105,11 +110,15 @@ namespace slskd.Transfers Configure(OptionsMonitor.CurrentValue); } + /// + /// Gets the global upload slot limit. + /// + public int GlobalSlots { get; private set; } = 0; + private Dictionary Groups { get; set; } = new Dictionary(); private int LastGlobalSlots { get; set; } private string LastOptionsHash { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private int MaxSlots { get; set; } = 0; private IOptionsMonitor OptionsMonitor { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private ConcurrentDictionary> Uploads { get; set; } = new ConcurrentDictionary>(); @@ -378,7 +387,7 @@ namespace slskd.Transfers return; } - MaxSlots = options.Global.Upload.Slots; + GlobalSlots = options.Global.Upload.Slots; // statically add built-in groups var groups = new List() @@ -392,7 +401,7 @@ namespace slskd.Transfers { Name = Application.PrivilegedGroup, Priority = 0, - Slots = MaxSlots, + Slots = GlobalSlots, UsedSlots = GetExistingUsedSlotsOrDefault(Application.PrivilegedGroup), Strategy = QueueStrategy.FirstInFirstOut, }, @@ -442,7 +451,7 @@ namespace slskd.Transfers try { - if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) + if (Groups.Values.Sum(g => g.UsedSlots) >= GlobalSlots) { return null; } -- cgit v1.2.3 From a88d21f6f1f2ef876e1957b0b9fde701fb716c68 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 31 Aug 2022 16:57:15 -0500 Subject: return the minimum of global slots and slots for a user's group --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 04dbab2e..9b68addf 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1038,7 +1038,7 @@ namespace slskd // wait until my first download starts. var info = new UserInfo( description: Options.Soulseek.Description, - uploadSlots: group.Slots, + uploadSlots: Math.Min(group.Slots, Transfers.Uploads.Queue.GlobalSlots), queueLength: forecastedPosition, hasFreeUploadSlot: forecastedPosition == 0); -- cgit v1.2.3 From f7093610aae6007468645666bd635531d20bd848 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 31 Aug 2022 17:11:14 -0500 Subject: don't expose GlobalSlots, constrain group slots --- src/slskd/Transfers/Uploads/UploadQueue.cs | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 0ab10a7e..e1e06e6d 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -34,11 +34,6 @@ namespace slskd.Transfers /// public interface IUploadQueue { - /// - /// Gets the global upload slot limit. - /// - int GlobalSlots { get; } - /// /// Awaits the start of an upload. /// @@ -110,11 +105,7 @@ namespace slskd.Transfers Configure(OptionsMonitor.CurrentValue); } - /// - /// Gets the global upload slot limit. - /// - public int GlobalSlots { get; private set; } = 0; - + private int GlobalSlots { get; set; } = 0; private Dictionary Groups { get; set; } = new Dictionary(); private int LastGlobalSlots { get; set; } private string LastOptionsHash { get; set; } @@ -409,7 +400,7 @@ namespace slskd.Transfers { Name = Application.DefaultGroup, Priority = options.Groups.Default.Upload.Priority, - Slots = options.Groups.Default.Upload.Slots, + Slots = Math.Min(options.Groups.Default.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(Application.DefaultGroup), Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Default.Upload.Strategy, true), }, @@ -417,7 +408,7 @@ namespace slskd.Transfers { Name = Application.LeecherGroup, Priority = options.Groups.Leechers.Upload.Priority, - Slots = options.Groups.Leechers.Upload.Slots, + Slots = Math.Min(options.Groups.Leechers.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(Application.LeecherGroup), Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Leechers.Upload.Strategy, true), }, @@ -428,7 +419,7 @@ namespace slskd.Transfers { Name = kvp.Key, Priority = kvp.Value.Upload.Priority, - Slots = kvp.Value.Upload.Slots, + Slots = Math.Min(kvp.Value.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(kvp.Key), Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true), })); -- cgit v1.2.3 From 632cb6e021993d95059c206c5a2a0c59c5a2d3bc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 31 Aug 2022 17:19:43 -0500 Subject: docs --- src/slskd/Transfers/Uploads/UploadQueue.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index e1e06e6d..54b9a6c3 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -442,6 +442,10 @@ namespace slskd.Transfers try { + // if the total number of used slots across all groups is greater than or equal to the configured + // number of global slots, just exit. we *could* proceed, but uploads would stack up behind the + // global semaphore in Soulseek.NET and we wouldn't be able to control the order in which those + // were processed, so don't do that. if (Groups.Values.Sum(g => g.UsedSlots) >= GlobalSlots) { return null; -- cgit v1.2.3 From b16366bc668aa39250baabd24c23f1ed21bd9bfb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 31 Aug 2022 17:19:54 -0500 Subject: refactor reporting of slots --- src/slskd/Application.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 9b68addf..35ae9df0 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -411,7 +411,7 @@ namespace slskd private async Task BrowseResponseResolver(string username, IPEndPoint endpoint) { Metrics.Browse.RequestsReceived.Inc(1); - + try { var sw = new Stopwatch(); @@ -931,6 +931,8 @@ namespace slskd // make sure our average speed (as reported by the server) is reasonably up to date await RefreshUserStatistics(); + var groupName = Users.GetGroup(username); + var group = Transfers.Uploads.Queue.GetGroupInfo(groupName); var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); Log.Information("[{Context}]: Sending {Count} records to {Username} for query '{Query}'", "SEARCH RESULT SENT", results.Count(), username, query.SearchText); @@ -941,7 +943,7 @@ namespace slskd Client.Username, token, uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, - freeUploadSlots: forecastedPosition == 0 ? 1 : 0, + freeUploadSlots: group.Slots - group.UsedSlots, queueLength: forecastedPosition, fileList: results); } @@ -1038,7 +1040,7 @@ namespace slskd // wait until my first download starts. var info = new UserInfo( description: Options.Soulseek.Description, - uploadSlots: Math.Min(group.Slots, Transfers.Uploads.Queue.GlobalSlots), + uploadSlots: group.Slots, queueLength: forecastedPosition, hasFreeUploadSlot: forecastedPosition == 0); -- cgit v1.2.3 From ded1017baa4a1a9c2b81804a5b0371e3c1884478 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 31 Aug 2022 17:26:15 -0500 Subject: make props r/w --- src/slskd/Transfers/Types/UploadGroup.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs index 22a98ae7..3a000a52 100644 --- a/src/slskd/Transfers/Types/UploadGroup.cs +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -20,10 +20,10 @@ namespace slskd.Transfers public sealed record UploadGroup { public string Name { get; init; } - public int Priority { get; init; } + public int Priority { get; set; } public bool SlotAvailable => UsedSlots < Slots; - public int Slots { get; init; } - public QueueStrategy Strategy { get; init; } + public int Slots { get; set; } + public QueueStrategy Strategy { get; set; } public int UsedSlots { get; set; } } } -- cgit v1.2.3 From b80e83b047b50f6e5261706c8571f4f19ddc540a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Sep 2022 08:41:18 -0500 Subject: bump Soulseek.NET to 5.1.2 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 8f0f99b2..7ff7df5e 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 3012245f5cd1d73b9579b43e5d89140884084f8c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Sep 2022 10:21:02 -0500 Subject: use HasFreeUploadSlot --- src/slskd/Application.cs | 4 +--- src/slskd/Search/Types/Response.cs | 4 ++-- src/web/src/components/Search/Detail/SearchDetail.js | 2 +- src/web/src/components/Search/Response.js | 2 +- 4 files changed, 5 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 35ae9df0..7fab470f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -931,8 +931,6 @@ namespace slskd // make sure our average speed (as reported by the server) is reasonably up to date await RefreshUserStatistics(); - var groupName = Users.GetGroup(username); - var group = Transfers.Uploads.Queue.GetGroupInfo(groupName); var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); Log.Information("[{Context}]: Sending {Count} records to {Username} for query '{Query}'", "SEARCH RESULT SENT", results.Count(), username, query.SearchText); @@ -943,7 +941,7 @@ namespace slskd Client.Username, token, uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, - freeUploadSlots: group.Slots - group.UsedSlots, + hasFreeUploadSlot: forecastedPosition == 0, queueLength: forecastedPosition, fileList: results); } diff --git a/src/slskd/Search/Types/Response.cs b/src/slskd/Search/Types/Response.cs index ea2e8993..7f72082d 100644 --- a/src/slskd/Search/Types/Response.cs +++ b/src/slskd/Search/Types/Response.cs @@ -24,7 +24,7 @@ namespace slskd.Search { public int FileCount { get; init; } public ICollection Files { get; init; } = new List(); - public int FreeUploadSlots { get; init; } + public bool HasFreeUploadSlot { get; init; } public int LockedFileCount { get; init; } public ICollection LockedFiles { get; init; } = new List(); public long QueueLength { get; init; } @@ -38,7 +38,7 @@ namespace slskd.Search { FileCount = searchResponse.FileCount, Files = searchResponse.Files.Select(file => File.FromSoulseekFile(file)).ToList(), - FreeUploadSlots = searchResponse.FreeUploadSlots, + HasFreeUploadSlot = searchResponse.HasFreeUploadSlot, LockedFileCount = searchResponse.LockedFileCount, LockedFiles = searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file)).ToList(), QueueLength = searchResponse.QueueLength, diff --git a/src/web/src/components/Search/Detail/SearchDetail.js b/src/web/src/components/Search/Detail/SearchDetail.js index af61c0ca..c8bba323 100644 --- a/src/web/src/components/Search/Detail/SearchDetail.js +++ b/src/web/src/components/Search/Detail/SearchDetail.js @@ -85,7 +85,7 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate }) .map(response => filterResponse({ response, filters })) .filter(r => r.fileCount + r.lockedFileCount > 0) - .filter(r => !(hideNoFreeSlots && r.freeUploadSlots === 0)) + .filter(r => !(hideNoFreeSlots && !r.hasFreeUploadSlot)) .sort((a, b) => { if (order === 'asc') { return a[field] - b[field]; diff --git a/src/web/src/components/Search/Response.js b/src/web/src/components/Search/Response.js index 6bc8feb0..1e3dfcbd 100644 --- a/src/web/src/components/Search/Response.js +++ b/src/web/src/components/Search/Response.js @@ -65,7 +65,7 @@ class Response extends Component { render = () => { let {response} = this.props; - let free = response.freeUploadSlots > 0; + let free = response.hasFreeUploadSlot; let { tree, downloadRequest, downloadError, isFolded } = this.state; -- cgit v1.2.3 From 81ef89924b586166e20fafaae76794755de2e3b0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Sep 2022 10:21:28 -0500 Subject: bump Soulseek.NET to 5.1.3 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 7ff7df5e..bfb2f3f0 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From e741d7346ec260c8acdc5cd09a1aa12c4645b3dd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Sep 2022 10:22:10 -0500 Subject: remove MinimumPeerFreeUploadSlots --- src/slskd/Search/API/DTO/SearchRequest.cs | 7 ----- src/slskd/Search/Extensions.cs | 44 +++++++++++++++---------------- 2 files changed, 21 insertions(+), 30 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/API/DTO/SearchRequest.cs b/src/slskd/Search/API/DTO/SearchRequest.cs index 4bbe189b..c81b2eeb 100644 --- a/src/slskd/Search/API/DTO/SearchRequest.cs +++ b/src/slskd/Search/API/DTO/SearchRequest.cs @@ -45,12 +45,6 @@ namespace slskd.Search.API /// public int? MaximumPeerQueueLength { get; set; } - /// - /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. - /// (Default = 0). - /// - public int? MinimumPeerFreeUploadSlots { get; set; } - /// /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). /// @@ -104,7 +98,6 @@ namespace slskd.Search.API fileLimit: FileLimit ?? def.FileLimit, filterResponses: FilterResponses ?? def.FilterResponses, minimumResponseFileCount: MinimumResponseFileCount ?? def.MinimumResponseFileCount, - minimumPeerFreeUploadSlots: MinimumPeerFreeUploadSlots ?? def.MinimumPeerFreeUploadSlots, maximumPeerQueueLength: MaximumPeerQueueLength ?? def.MaximumPeerQueueLength, minimumPeerUploadSpeed: MinimumPeerUploadSpeed ?? def.MinimumPeerUploadSpeed, responseFilter: responseFilter, diff --git a/src/slskd/Search/Extensions.cs b/src/slskd/Search/Extensions.cs index 5fc53f88..6a034e0a 100644 --- a/src/slskd/Search/Extensions.cs +++ b/src/slskd/Search/Extensions.cs @@ -39,17 +39,16 @@ namespace slskd.Search responseReceived ??= (args) => { }; return new SearchOptions( - options.SearchTimeout, - options.ResponseLimit, - options.FilterResponses, - options.MinimumResponseFileCount, - options.MinimumPeerFreeUploadSlots, - options.MaximumPeerQueueLength, - options.MinimumPeerUploadSpeed, - options.FileLimit, - options.RemoveSingleCharacterSearchTerms, - options.ResponseFilter, - options.FileFilter, + searchTimeout: options.SearchTimeout, + responseLimit: options.ResponseLimit, + filterResponses: options.FilterResponses, + minimumResponseFileCount: options.MinimumResponseFileCount, + maximumPeerQueueLength: options.MaximumPeerQueueLength, + minimumPeerUploadSpeed: options.MinimumPeerUploadSpeed, + fileLimit: options.FileLimit, + removeSingleCharacterSearchTerms: options.RemoveSingleCharacterSearchTerms, + responseFilter: options.ResponseFilter, + fileFilter: options.FileFilter, stateChanged: (args) => { if (options.StateChanged != null) @@ -83,19 +82,18 @@ namespace slskd.Search Func fileFilter = null) { return new SearchOptions( - options.SearchTimeout, - options.ResponseLimit, + searchTimeout: options.SearchTimeout, + responseLimit: options.ResponseLimit, filterResponses: options.FilterResponses || responseFilter != null || fileFilter != null, - options.MinimumResponseFileCount, - options.MinimumPeerFreeUploadSlots, - options.MaximumPeerQueueLength, - options.MinimumPeerUploadSpeed, - options.FileLimit, - options.RemoveSingleCharacterSearchTerms, - responseFilter, - fileFilter, - options.StateChanged, - options.ResponseReceived); + minimumResponseFileCount: options.MinimumResponseFileCount, + maximumPeerQueueLength: options.MaximumPeerQueueLength, + minimumPeerUploadSpeed: options.MinimumPeerUploadSpeed, + fileLimit: options.FileLimit, + removeSingleCharacterSearchTerms: options.RemoveSingleCharacterSearchTerms, + responseFilter: responseFilter, + fileFilter: fileFilter, + stateChanged: options.StateChanged, + responseReceived: options.ResponseReceived); } /// -- cgit v1.2.3 From 7d4c8156d55547c7106ee953d0a33d2a32e518cb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 17:14:32 -0500 Subject: add NormalizePath() --- src/slskd/Common/CommonExtensions.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 65949016..f9c597f8 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -239,6 +239,16 @@ namespace slskd .Build() .Deserialize(str); + public static string NormalizePath(this string filename) + { + if (Path.DirectorySeparatorChar == '\\') + { + return filename; + } + + return filename.Replace(Path.DirectorySeparatorChar, '\\'); + } + /// /// Converts a fully qualified remote filename to a local filename based in the provided /// , swapping directory characters for those specific to the local OS, removing any -- cgit v1.2.3 From b7eacb3a513038ec5c7d205668042c920ca56dc2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 17:14:58 -0500 Subject: normalize filenames during scan --- src/slskd/Shares/SharedFileCache.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 6e38ee31..070440c3 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -272,7 +272,9 @@ namespace slskd.Shares IgnoreInaccessible = true, RecurseSubdirectories = false, }) - .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) + .Select(filename => SoulseekFileFactory.Create( + filename: filename.NormalizePath(), + maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePath())) .ToDictionary(file => file.Filename, file => file); addedFiles = newFiles.Count; -- cgit v1.2.3 From 6735bf4f1b984055170130753788de67d648c7d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 22:31:14 -0500 Subject: localize/normalize --- src/slskd/Common/CommonExtensions.cs | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index f9c597f8..cc657919 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -239,16 +239,6 @@ namespace slskd .Build() .Deserialize(str); - public static string NormalizePath(this string filename) - { - if (Path.DirectorySeparatorChar == '\\') - { - return filename; - } - - return filename.Replace(Path.DirectorySeparatorChar, '\\'); - } - /// /// Converts a fully qualified remote filename to a local filename based in the provided /// , swapping directory characters for those specific to the local OS, removing any @@ -264,11 +254,22 @@ namespace slskd } /// - /// Converts the given path to the local format (normalizes path separators). + /// Converts the given path to the normalized format (normalizes path separators to backslashes) + /// + /// The path to convert. + /// The converted path. + public static string NormalizePath(this string path) + { + return path.Replace('/', '\\'); + } + + + /// + /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). /// /// The path to convert. /// The converted path. - public static string ToLocalOSPath(this string path) + public static string LocalizePath(this string path) { return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); } @@ -288,7 +289,7 @@ namespace slskd } // normalize path separators - var localizedRemoteFilename = remoteFilename.ToLocalOSPath(); + var localizedRemoteFilename = remoteFilename.LocalizePath(); var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); -- cgit v1.2.3 From 6cb9f1ccc72cad333dec5f7a7b0fdf5bc5691921 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 22:31:33 -0500 Subject: LocalizePath() --- src/slskd/Core/Options.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 6a435db1..259977b6 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -363,16 +363,16 @@ namespace slskd { var results = new List(); - bool IsBlankPath(string share) => Regex.IsMatch(share.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])$"); + bool IsBlankPath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])$"); Shared.Where(share => IsBlankPath(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} doees not specify a path"))); - bool IsRootMount(string share) => Regex.IsMatch(share.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])/$"); + bool IsRootMount(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])/$"); Shared.Where(share => IsRootMount(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported."))); // starts with '/', 'X:', or '\\' - bool IsAbsolutePath(string share) => Regex.IsMatch(share.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); + bool IsAbsolutePath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); Shared.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); -- cgit v1.2.3 From 5764ed3d109efc18252cfb90234d30ebed2e64b1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 22:39:14 -0500 Subject: remove redundant localization --- src/slskd/Transfers/Uploads/UploadService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 740c6237..e6b55319 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -58,7 +58,6 @@ namespace slskd.Transfers.Uploads /// /// Gets the upload governor. /// - public IUploadGovernor Governor { get; init; } /// /// Gets the upload queue. @@ -114,7 +113,7 @@ namespace slskd.Transfers.Uploads try { - localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); + localFilename = await Shares.ResolveFilenameAsync(filename); fileInfo = new FileInfo(localFilename); -- cgit v1.2.3 From 951aca1fa28981901f52d8fc0703d27b84add8be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 22:39:59 -0500 Subject: localize paths while listing and resolving --- src/slskd/Shares/SharedFileCache.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 070440c3..42d98a90 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -364,6 +364,8 @@ namespace slskd.Shares /// The contents of the directory. public Directory List(string directory) { + directory = directory.LocalizePath(); + if (!State.CurrentValue.Filled) { if (State.CurrentValue.Filling) @@ -396,7 +398,7 @@ namespace slskd.Shares /// The unmasked filename. public string Resolve(string filename) { - filename = filename.ToLocalOSPath(); + filename = filename.LocalizePath(); // ensure this is a tracked file if (!MaskedFiles.TryGetValue(filename, out _)) -- cgit v1.2.3 From fe05503e84eeb7063e19bfa59ee5e02a9b72613e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 23:04:20 -0500 Subject: normalize paths in browse response --- src/slskd/Shares/SharedFileCache.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 42d98a90..dc04957d 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -137,7 +137,7 @@ namespace slskd.Shares var groups = MaskedFiles .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Directory(g.Key, g.Select(g => + .Select(g => new Directory(g.Key.NormalizePath(), g.Select(g => { var f = g.Value; return new File( -- cgit v1.2.3 From 70401959ddc59236a59365b19efd7877c6c381a0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 23:04:45 -0500 Subject: don't normalize when inserting files --- src/slskd/Shares/SharedFileCache.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index dc04957d..2e6ad817 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -273,8 +273,8 @@ namespace slskd.Shares RecurseSubdirectories = false, }) .Select(filename => SoulseekFileFactory.Create( - filename: filename.NormalizePath(), - maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePath())) + filename: filename, + maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) .ToDictionary(file => file.Filename, file => file); addedFiles = newFiles.Count; -- cgit v1.2.3 From 0e3d7622a2f72ecc5e82eeb04a8b8d9775394db2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 23:05:07 -0500 Subject: normalize directory listing --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 2e6ad817..f5b05509 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -387,7 +387,7 @@ namespace slskd.Shares f.Attributes); }); - return new Directory(directory, files); + return new Directory(directory.NormalizePath(), files); } /// -- cgit v1.2.3 From dafd43c7c9a805b8033e5710cbaef55da92c8d55 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 23:05:45 -0500 Subject: normalize search responses --- src/slskd/Shares/SharedFileCache.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index f5b05509..013ce202 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -478,7 +478,15 @@ namespace slskd.Shares try { - return results.Select(r => MaskedFiles[r]).ToList(); + return results + .Select(r => MaskedFiles[r]) + .Select(f => new File( + f.Code, + f.Filename.NormalizePath(), + f.Size, + f.Extension, + f.Attributes)) + .ToList(); } catch (Exception ex) { -- cgit v1.2.3 From 4b18fd9ee437d472b3922191afe0e49ae16e286a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Sep 2022 23:06:11 -0500 Subject: how did that get deleted? --- src/slskd/Transfers/Uploads/UploadService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index e6b55319..fba6bc4d 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -58,6 +58,7 @@ namespace slskd.Transfers.Uploads /// /// Gets the upload governor. /// + public IUploadGovernor Governor { get; init; } /// /// Gets the upload queue. -- cgit v1.2.3 From 282ab06901b04ca83c570d9f85d646db0ef9d6c9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 12:36:26 -0500 Subject: normalize/localize paths in ShareService --- src/slskd/Shares/IShareService.cs | 4 +++- src/slskd/Shares/ShareService.cs | 45 ++++++++++++++++++++++++++++++++------- 2 files changed, 40 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 16f1a890..a2eeed92 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using System.IO; + namespace slskd.Shares { using System.Collections.Generic; @@ -58,7 +60,7 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - Task ResolveFilenameAsync(string remoteFilename); + Task ResolveFileAsync(string remoteFilename); /// /// Searches the cache for the specified and returns the matching files. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 60fbdda3..60b69967 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -15,6 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using System.IO; using Microsoft.Extensions.Options; namespace slskd.Shares @@ -86,7 +87,12 @@ namespace slskd.Shares /// /// The entire contents of the share. public Task> BrowseAsync() - => Task.FromResult(Cache.Browse()); + { + var results = Cache.Browse(); + var normalizedResults = results.Select(r => new Directory(r.Name.NormalizePath(), r.Files)); + + return Task.FromResult(normalizedResults); + } /// /// Returns the contents of the specified . @@ -94,7 +100,12 @@ namespace slskd.Shares /// The directory for which the contents are to be listed. /// The contents of the directory. public Task ListDirectoryAsync(string directory) - => Task.FromResult(Cache.List(directory)); + { + var list = Cache.List(directory.LocalizePath()); + var normalizedList = new Directory(list.Name.NormalizePath(), list.Files); + + return Task.FromResult(normalizedList); + } /// /// Resolves the local filename of the specified , if the mask is associated with a @@ -105,16 +116,25 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - public Task ResolveFilenameAsync(string remoteFilename) + public Task ResolveFileAsync(string remoteFilename) { - var resolvedFilename = Cache.Resolve(remoteFilename); + var resolvedFilename = Cache.Resolve(remoteFilename.LocalizePath()); if (string.IsNullOrEmpty(resolvedFilename)) { - throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a local file."); + throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a local file"); } - return Task.FromResult(resolvedFilename); + var fileInfo = new FileInfo(resolvedFilename); + + if (!fileInfo.Exists) + { + // the shared file cache has divered from the physical filesystem; the user needs to perform a scan to reconcile. + State.SetValue(state => state with { ScanPending = true }); + throw new NotFoundException($"The resolved file '{resolvedFilename}' could not be located on disk. A share scan should be performed."); + } + + return Task.FromResult(fileInfo); } /// @@ -122,8 +142,17 @@ namespace slskd.Shares /// /// The query for which to search. /// The matching files. - public Task> SearchAsync(SearchQuery query) - => Cache.SearchAsync(query); + public async Task> SearchAsync(SearchQuery query) + { + var results = await Cache.SearchAsync(query); + + return results.Select(r => new File( + r.Code, + r.Filename.NormalizePath(), + r.Size, + r.Extension, + r.Attributes)); + } /// /// Starts a scan of the configured shares. -- cgit v1.2.3 From 1b81de8d8c90e3377ab0b8102b099ccadbc64155 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 12:36:59 -0500 Subject: tweak docs --- src/slskd/Common/CommonExtensions.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index cc657919..6f39d17f 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -254,7 +254,7 @@ namespace slskd } /// - /// Converts the given path to the normalized format (normalizes path separators to backslashes) + /// Converts the given path to the normalized format (normalizes path separators to backslashes). /// /// The path to convert. /// The converted path. @@ -263,7 +263,6 @@ namespace slskd return path.Replace('/', '\\'); } - /// /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). /// -- cgit v1.2.3 From 6b966b8528c2beb35747e73126f83c48f8355e74 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 12:37:24 -0500 Subject: remove normalization from SharedFileCache --- src/slskd/Shares/SharedFileCache.cs | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 013ce202..3a41f61b 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -137,7 +137,7 @@ namespace slskd.Shares var groups = MaskedFiles .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Directory(g.Key.NormalizePath(), g.Select(g => + .Select(g => new Directory(g.Key, g.Select(g => { var f = g.Value; return new File( @@ -272,9 +272,7 @@ namespace slskd.Shares IgnoreInaccessible = true, RecurseSubdirectories = false, }) - .Select(filename => SoulseekFileFactory.Create( - filename: filename, - maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) + .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) .ToDictionary(file => file.Filename, file => file); addedFiles = newFiles.Count; @@ -364,8 +362,6 @@ namespace slskd.Shares /// The contents of the directory. public Directory List(string directory) { - directory = directory.LocalizePath(); - if (!State.CurrentValue.Filled) { if (State.CurrentValue.Filling) @@ -387,7 +383,7 @@ namespace slskd.Shares f.Attributes); }); - return new Directory(directory.NormalizePath(), files); + return new Directory(directory, files); } /// @@ -398,8 +394,6 @@ namespace slskd.Shares /// The unmasked filename. public string Resolve(string filename) { - filename = filename.LocalizePath(); - // ensure this is a tracked file if (!MaskedFiles.TryGetValue(filename, out _)) { @@ -480,12 +474,6 @@ namespace slskd.Shares { return results .Select(r => MaskedFiles[r]) - .Select(f => new File( - f.Code, - f.Filename.NormalizePath(), - f.Size, - f.Extension, - f.Attributes)) .ToList(); } catch (Exception ex) -- cgit v1.2.3 From 04729b240adcebee7beaa2894701fdbe0da20b7e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 12:38:24 -0500 Subject: use FileInfo from shares service --- src/slskd/Transfers/Uploads/UploadService.cs | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index fba6bc4d..396eab10 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -107,21 +107,13 @@ namespace slskd.Transfers.Uploads /// The operation context. public async Task EnqueueAsync(string username, string filename) { - string localFilename; FileInfo fileInfo = default; Log.Information("[{Context}] {Username} requested {Filename}", "UPLOAD REQUESTED", username, filename); try { - localFilename = await Shares.ResolveFilenameAsync(filename); - - fileInfo = new FileInfo(localFilename); - - if (!fileInfo.Exists) - { - throw new NotFoundException(); - } + fileInfo = await Shares.ResolveFileAsync(filename.LocalizePath()); } catch (NotFoundException) { @@ -130,12 +122,12 @@ namespace slskd.Transfers.Uploads } // find existing records for this username and file that haven't been removed from the UI - var existingRecords = List(t => t.Username == username && t.Filename == localFilename && !t.Removed); + var existingRecords = List(t => t.Username == username && t.Filename == fileInfo.FullName && !t.Removed); // check whether any of these records is in a non-complete state and bail out if so if (existingRecords.Any(t => !t.State.HasFlag(TransferStates.Completed))) { - Log.Information("Upload {Filename} to {Username} is already queued or in progress", localFilename, username); + Log.Information("Upload {Filename} to {Username} is already queued or in progress", fileInfo.FullName, username); return; } @@ -146,7 +138,7 @@ namespace slskd.Transfers.Uploads Id = id, Username = username, Direction = TransferDirection.Upload, - Filename = localFilename, + Filename = fileInfo.FullName, Size = fileInfo.Length, StartOffset = 0, // potentially updated later during handshaking RequestedAt = DateTime.UtcNow, @@ -192,7 +184,7 @@ namespace slskd.Transfers.Uploads var topts = new TransferOptions( stateChanged: (args) => { - Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, username, args.PreviousState, args.Transfer.State); + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", fileInfo.FullName, username, args.PreviousState, args.Transfer.State); if (Application.IsShuttingDown) { -- cgit v1.2.3 From 09345a8c1c1cf3f2bf29604d8653a68cc8b8c911 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 12:40:06 -0500 Subject: defer normalization --- src/slskd/Application.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 7fab470f..e4d47bb1 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -417,8 +417,7 @@ namespace slskd var sw = new Stopwatch(); sw.Start(); - var directories = (await Shares.BrowseAsync()) - .Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes + var directories = await Shares.BrowseAsync(); sw.Stop(); -- cgit v1.2.3 From 76676173ca331a3d6413cfd776abeda4d31ac675 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 16:52:29 -0500 Subject: derive a new File with a property to store the physical file location --- src/slskd/Shares/Types/File.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/slskd/Shares/Types/File.cs (limited to 'src') diff --git a/src/slskd/Shares/Types/File.cs b/src/slskd/Shares/Types/File.cs new file mode 100644 index 00000000..e7740613 --- /dev/null +++ b/src/slskd/Shares/Types/File.cs @@ -0,0 +1,33 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System.Collections.Generic; + using Soulseek; + + public class File : Soulseek.File + { + public File(int code, string filename, long size, string extension, IEnumerable attributeList = null, string originalFilename = null) + : base(code, filename, size, extension, attributeList) + { + OriginalFilename = originalFilename; + } + + public string OriginalFilename { get; set; } + } +} -- cgit v1.2.3 From 4c8bd648b6250d6eb5603420fa6280e948a00dd6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 16:53:02 -0500 Subject: stash OriginalFilename if we manipulate the path. use this when resolving if it is set --- src/slskd/Shares/SharedFileCache.cs | 43 +++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 3a41f61b..31a179f2 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -279,20 +279,38 @@ namespace slskd.Shares // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var file in newFiles) + foreach (var record in newFiles) { - if (filters.Any(filter => filter.IsMatch(file.Key))) + var (key, value) = record; + + if (filters.Any(filter => filter.IsMatch(key))) { filteredFiles++; continue; } - if (files.ContainsKey(file.Key)) + if (files.ContainsKey(key)) + { + Log.Warning($"File {key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); + } + + // if we're on an operating system that uses forward slashes, it is possible for filenames to contain + // backslashes. because we normalize directory separators to backslashes before we send results to the network, + // we need to replace any backslashes with a placeholder to prevent things from breaking. we'll capture the original + // filename if we do this so we can resolve the original filename given the replacement without doing any guessing. + if (Path.DirectorySeparatorChar == '/' && value.Filename.Contains('\\')) { - Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); + // todo: store OriginalFilename for all files once masked filenames are stored in the db. we aren't doing this now to reduce memory footprint. + value = new File( + value.Code, + value.Filename.Replace('\\', '_'), + value.Size, + value.Extension, + value.Attributes, + originalFilename: value.Filename); } - files[file.Key] = file.Value; + files[key] = value; } } catch (Exception ex) @@ -395,11 +413,24 @@ namespace slskd.Shares public string Resolve(string filename) { // ensure this is a tracked file - if (!MaskedFiles.TryGetValue(filename, out _)) + if (!MaskedFiles.TryGetValue(filename, out var maskedRecord)) { return null; } + // if the OriginalFilename property of the record was set during the scan, + // one or more characters was substituted, and we can't trust the manipulated + // path to find the correct file without some degree of guessing. return the + // value of OriginalFilename which definitively points to the location on disk. + if (!string.IsNullOrEmpty(maskedRecord.Filename)) + { + // todo: use OriginalFilename for all files once masked files are stored in the db + return maskedRecord.OriginalFilename; + } + + // if OriginalFilename isn't set, derive the location of the file from the masked + // filename and share configuration. we don't store OriginalFilename for all records + // to reduce memory footprint var resolved = filename; // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a -- cgit v1.2.3 From 7f26c010f6282d9ea6e597d74441a27d4dade869 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 16:58:19 -0500 Subject: log replacements --- src/slskd/Shares/SharedFileCache.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 31a179f2..eb0450d8 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -308,6 +308,8 @@ namespace slskd.Shares value.Extension, value.Attributes, originalFilename: value.Filename); + + Log.Warning($"Substituting {value.Filename} for {value.Filename.Replace('\\', '_')}"); } files[key] = value; -- cgit v1.2.3 From 0e74f054f89fba1037536c80713e889a6379e928 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 17:01:03 -0500 Subject: tweak --- src/slskd/Shares/SharedFileCache.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index eb0450d8..73e82e40 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -300,6 +300,8 @@ namespace slskd.Shares // filename if we do this so we can resolve the original filename given the replacement without doing any guessing. if (Path.DirectorySeparatorChar == '/' && value.Filename.Contains('\\')) { + Log.Warning($"Substituting {value.Filename} for {value.Filename.Replace('\\', '_')}"); + // todo: store OriginalFilename for all files once masked filenames are stored in the db. we aren't doing this now to reduce memory footprint. value = new File( value.Code, @@ -309,7 +311,6 @@ namespace slskd.Shares value.Attributes, originalFilename: value.Filename); - Log.Warning($"Substituting {value.Filename} for {value.Filename.Replace('\\', '_')}"); } files[key] = value; -- cgit v1.2.3 From 5387e5bde7cef5c8546f6bf5dd024dc61dd42b25 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 17:05:21 -0500 Subject: replace the key too --- src/slskd/Shares/SharedFileCache.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 73e82e40..a8a8badb 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -300,9 +300,10 @@ namespace slskd.Shares // filename if we do this so we can resolve the original filename given the replacement without doing any guessing. if (Path.DirectorySeparatorChar == '/' && value.Filename.Contains('\\')) { - Log.Warning($"Substituting {value.Filename} for {value.Filename.Replace('\\', '_')}"); + Log.Warning($"Substituting {value.Filename} with {value.Filename.Replace('\\', '_')}"); // todo: store OriginalFilename for all files once masked filenames are stored in the db. we aren't doing this now to reduce memory footprint. + key = key.Replace('\\', '_'); value = new File( value.Code, value.Filename.Replace('\\', '_'), @@ -310,7 +311,6 @@ namespace slskd.Shares value.Extension, value.Attributes, originalFilename: value.Filename); - } files[key] = value; -- cgit v1.2.3 From 594718ccb9925ee722bdd3b9928839acd7b6a821 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 17:08:38 -0500 Subject: more logging --- src/slskd/Shares/SharedFileCache.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index a8a8badb..2bb495b5 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -415,9 +415,12 @@ namespace slskd.Shares /// The unmasked filename. public string Resolve(string filename) { + Log.Warning($"Resolving: {filename}"); + // ensure this is a tracked file if (!MaskedFiles.TryGetValue(filename, out var maskedRecord)) { + Log.Warning("Not tracked"); return null; } @@ -427,6 +430,7 @@ namespace slskd.Shares // value of OriginalFilename which definitively points to the location on disk. if (!string.IsNullOrEmpty(maskedRecord.Filename)) { + Log.Warning($"OriginalFilename populated: {}"); // todo: use OriginalFilename for all files once masked files are stored in the db return maskedRecord.OriginalFilename; } -- cgit v1.2.3 From 7ba85bf91c35dd8a365f2680329ef152ed88ee8c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 17:10:00 -0500 Subject: fix bug --- src/slskd/Shares/SharedFileCache.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 2bb495b5..e7b1cee5 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -428,9 +428,9 @@ namespace slskd.Shares // one or more characters was substituted, and we can't trust the manipulated // path to find the correct file without some degree of guessing. return the // value of OriginalFilename which definitively points to the location on disk. - if (!string.IsNullOrEmpty(maskedRecord.Filename)) + if (!string.IsNullOrEmpty(maskedRecord.OriginalFilename)) { - Log.Warning($"OriginalFilename populated: {}"); + Log.Warning($"OriginalFilename populated: {maskedRecord.OriginalFilename}"); // todo: use OriginalFilename for all files once masked files are stored in the db return maskedRecord.OriginalFilename; } -- cgit v1.2.3 From dd3e83bd845043cd86d196f5f51eca3756e9c68c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Sep 2022 17:14:47 -0500 Subject: still need to build the filename from share --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index e7b1cee5..666fd16c 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -432,7 +432,7 @@ namespace slskd.Shares { Log.Warning($"OriginalFilename populated: {maskedRecord.OriginalFilename}"); // todo: use OriginalFilename for all files once masked files are stored in the db - return maskedRecord.OriginalFilename; + filename = maskedRecord.OriginalFilename; } // if OriginalFilename isn't set, derive the location of the file from the masked -- cgit v1.2.3 From e609fe8e4e7fca623a939cb6ecf73979a8666a45 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Sep 2022 11:41:16 -0500 Subject: try a different approach --- src/slskd/Shares/SharedFileCache.cs | 50 +++++-------------------------------- src/slskd/Shares/Types/File.cs | 33 ------------------------ 2 files changed, 6 insertions(+), 77 deletions(-) delete mode 100644 src/slskd/Shares/Types/File.cs (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 666fd16c..3a41f61b 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -279,41 +279,20 @@ namespace slskd.Shares // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var record in newFiles) + foreach (var file in newFiles) { - var (key, value) = record; - - if (filters.Any(filter => filter.IsMatch(key))) + if (filters.Any(filter => filter.IsMatch(file.Key))) { filteredFiles++; continue; } - if (files.ContainsKey(key)) - { - Log.Warning($"File {key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); - } - - // if we're on an operating system that uses forward slashes, it is possible for filenames to contain - // backslashes. because we normalize directory separators to backslashes before we send results to the network, - // we need to replace any backslashes with a placeholder to prevent things from breaking. we'll capture the original - // filename if we do this so we can resolve the original filename given the replacement without doing any guessing. - if (Path.DirectorySeparatorChar == '/' && value.Filename.Contains('\\')) + if (files.ContainsKey(file.Key)) { - Log.Warning($"Substituting {value.Filename} with {value.Filename.Replace('\\', '_')}"); - - // todo: store OriginalFilename for all files once masked filenames are stored in the db. we aren't doing this now to reduce memory footprint. - key = key.Replace('\\', '_'); - value = new File( - value.Code, - value.Filename.Replace('\\', '_'), - value.Size, - value.Extension, - value.Attributes, - originalFilename: value.Filename); + Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); } - files[key] = value; + files[file.Key] = file.Value; } } catch (Exception ex) @@ -415,29 +394,12 @@ namespace slskd.Shares /// The unmasked filename. public string Resolve(string filename) { - Log.Warning($"Resolving: {filename}"); - // ensure this is a tracked file - if (!MaskedFiles.TryGetValue(filename, out var maskedRecord)) + if (!MaskedFiles.TryGetValue(filename, out _)) { - Log.Warning("Not tracked"); return null; } - // if the OriginalFilename property of the record was set during the scan, - // one or more characters was substituted, and we can't trust the manipulated - // path to find the correct file without some degree of guessing. return the - // value of OriginalFilename which definitively points to the location on disk. - if (!string.IsNullOrEmpty(maskedRecord.OriginalFilename)) - { - Log.Warning($"OriginalFilename populated: {maskedRecord.OriginalFilename}"); - // todo: use OriginalFilename for all files once masked files are stored in the db - filename = maskedRecord.OriginalFilename; - } - - // if OriginalFilename isn't set, derive the location of the file from the masked - // filename and share configuration. we don't store OriginalFilename for all records - // to reduce memory footprint var resolved = filename; // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a diff --git a/src/slskd/Shares/Types/File.cs b/src/slskd/Shares/Types/File.cs deleted file mode 100644 index e7740613..00000000 --- a/src/slskd/Shares/Types/File.cs +++ /dev/null @@ -1,33 +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.Collections.Generic; - using Soulseek; - - public class File : Soulseek.File - { - public File(int code, string filename, long size, string extension, IEnumerable attributeList = null, string originalFilename = null) - : base(code, filename, size, extension, attributeList) - { - OriginalFilename = originalFilename; - } - - public string OriginalFilename { get; set; } - } -} -- cgit v1.2.3 From 731b371d25e84536745f3987cc83344d8e7e0262 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Sep 2022 12:23:54 -0500 Subject: log warning for unsupported directories and files --- src/slskd/Shares/SharedFileCache.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 3a41f61b..9902c951 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -253,6 +253,12 @@ namespace slskd.Shares { Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count); + if (Path.DirectorySeparatorChar == '/' && directory.Contains('\\')) + { + Log.Warning("Directory name {Directory} contains one or more backslashes, which are not currently supported. This directory will not be shared.", directory); + continue; + } + var addedFiles = 0L; var filteredFiles = 0L; @@ -287,6 +293,12 @@ namespace slskd.Shares continue; } + if (Path.DirectorySeparatorChar == '/' && file.Value.Filename.Contains('\\')) + { + Log.Warning("Filename {Filename} contains one or more backslashes, which are not currently supported. This file will not be shared.", file.Value.Filename); + continue; + } + if (files.ContainsKey(file.Key)) { Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); -- cgit v1.2.3 From d3bfd9a611e6c953a44abae6a544b0e1ec4bbd2d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Sep 2022 08:04:54 -0500 Subject: fix bug with cancellation --- src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++++++------ src/slskd/Transfers/Uploads/UploadService.cs | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c6b62bc8..467ab4b3 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -154,9 +154,9 @@ namespace slskd.Transfers.Downloads using var rateLimiter = new RateLimiter(250, flushOnDispose: true); var syncRoot = new SemaphoreSlim(1, 1); - void SynchronizedUpdate(Transfer transfer) + void SynchronizedUpdate(Transfer transfer, bool cancellable = true) { - syncRoot.Wait(cts.Token); + syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); try { @@ -215,7 +215,7 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, cancellable: false); // this would be the ideal place to hook in a generic post-download task processor for now, we'll // just carry out hard coded behavior. these carry the risk of failing the transfer, and i could @@ -227,14 +227,14 @@ namespace slskd.Transfers.Downloads _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads)); } } - catch (TaskCanceledException ex) + catch (OperationCanceledException ex) { transfer.EndedAt = DateTime.UtcNow; transfer.Exception = ex.Message; transfer.State = TransferStates.Completed | TransferStates.Cancelled; // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, cancellable: false); throw; } @@ -247,7 +247,7 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, cancellable: false); throw; } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 396eab10..c3cfe2fb 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -158,9 +158,9 @@ namespace slskd.Transfers.Uploads using var rateLimiter = new RateLimiter(250, flushOnDispose: true); var syncRoot = new SemaphoreSlim(1, 1); - void SynchronizedUpdate(Transfer transfer) + void SynchronizedUpdate(Transfer transfer, bool cancellable = true) { - syncRoot.Wait(cts.Token); + syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); try { @@ -228,16 +228,16 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(completedTransfer); //todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, cancellable: false); } - catch (TaskCanceledException ex) + catch (OperationCanceledException ex) { transfer.EndedAt = DateTime.UtcNow; transfer.Exception = ex.Message; transfer.State = TransferStates.Completed | TransferStates.Cancelled; // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, cancellable: false); throw; } @@ -250,7 +250,7 @@ namespace slskd.Transfers.Uploads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, cancellable: false); throw; } -- cgit v1.2.3 From cc06d0f0f83fe3f9313a9e9e91e3cca9b8db7cf3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 6 Sep 2022 21:59:39 -0500 Subject: add ConnectionStrings record --- src/slskd/Core/ConnectionStrings.cs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/slskd/Core/ConnectionStrings.cs (limited to 'src') diff --git a/src/slskd/Core/ConnectionStrings.cs b/src/slskd/Core/ConnectionStrings.cs new file mode 100644 index 00000000..e5bd4f05 --- /dev/null +++ b/src/slskd/Core/ConnectionStrings.cs @@ -0,0 +1,29 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Application connection strings. + /// + public record ConnectionStrings + { + public string Transfers { get; init; } + public string Shares { get; init; } + public string Search { get; init; } + } +} -- cgit v1.2.3 From 51116cc1c198e9853860d168d2e5f96ec0edd263 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 6 Sep 2022 22:01:14 -0500 Subject: add DataDirectory, minimize magic strings --- src/slskd/Program.cs | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 541f0f00..371f60bd 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -45,7 +45,6 @@ namespace slskd using Microsoft.Extensions.FileProviders.Physical; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; - using Prometheus; using Prometheus.DotNetRuntime; using Prometheus.SystemMetrics; using Serilog; @@ -160,6 +159,16 @@ namespace slskd [EnvironmentVariable("CONFIG")] public static string ConfigurationFile { get; private set; } = null; + /// + /// Gets the connection strings for application databases. + /// + public static ConnectionStrings ConnectionStrings { get; private set; } = null; + + /// + /// Gets the path where persistent data is saved. + /// + public static string DataDirectory { get; private set; } = null; + /// /// Gets the default fully qualified path to the configuration file. /// @@ -247,6 +256,15 @@ namespace slskd // and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; + DataDirectory = Path.Combine(AppDirectory, "data"); + + 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={Path.Combine(DataDirectory, "shares.db")};Cache=shared", + }; + DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml"); DefaultDownloadsDirectory = Path.Combine(AppDirectory, "downloads"); DefaultIncompleteDirectory = Path.Combine(AppDirectory, "incomplete"); @@ -260,7 +278,7 @@ namespace slskd try { VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); - VerifyDirectory(Path.Combine(AppDirectory, "data"), createIfMissing: true, verifyWriteable: true); + VerifyDirectory(DataDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(DefaultDownloadsDirectory, createIfMissing: true, verifyWriteable: true); VerifyDirectory(DefaultIncompleteDirectory, createIfMissing: true, verifyWriteable: true); } @@ -449,8 +467,8 @@ namespace slskd ConfigureSQLite(); - services.AddDbContext("search.db"); - services.AddDbContext("transfers.db"); + services.AddDbContext(ConnectionStrings.Search); + services.AddDbContext(ConnectionStrings.Transfers); services.AddSingleton(); services.AddSingleton(); @@ -512,7 +530,7 @@ namespace slskd using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); services.AddDataProtection() - .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppDirectory, "data", ".DataProtection-Keys"))); + .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, ".DataProtection-Keys"))); var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); @@ -838,7 +856,7 @@ namespace slskd commandLine: Environment.CommandLine); } - private static IServiceCollection AddDbContext(this IServiceCollection services, string filename) + private static IServiceCollection AddDbContext(this IServiceCollection services, string connectionString) where T : DbContext { Log.Debug("Initializing database context {Name}", typeof(T).Name); @@ -847,7 +865,7 @@ namespace slskd { services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)};Cache=shared;Pooling=True;"); + options.UseSqlite(connectionString); if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) { -- cgit v1.2.3 From 3ff332115cd5bd9e1942bea43dcfed888f348c2f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 6 Sep 2022 23:22:44 -0500 Subject: wip --- src/slskd/Shares/SharedFileCache.cs | 110 ++++++++++++++++++++++++++++-------- 1 file changed, 88 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 9902c951..bded2a75 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -99,7 +99,6 @@ namespace slskd.Shares public IStateMonitor StateMonitor => State; private ILogger Log { get; } = Serilog.Log.ForContext(); - private HashSet MaskedDirectories { get; set; } private Dictionary MaskedFiles { get; set; } private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } @@ -130,12 +129,12 @@ 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 MaskedDirectories) + foreach (var directory in ListDirectories()) { directories.TryAdd(directory, new Directory(directory)); } - var groups = MaskedFiles + var groups = ListFiles() .GroupBy(f => Path.GetDirectoryName(f.Key)) .Select(g => new Directory(g.Key, g.Select(g => { @@ -188,6 +187,7 @@ namespace slskd.Shares ResetCache(); + var scannedAt = DateTime.UtcNow; var sw = new Stopwatch(); var swSnapshot = 0L; sw.Start(); @@ -265,6 +265,7 @@ namespace slskd.Shares var share = Shares.First(share => directory.StartsWith(share.LocalPath)); maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized // filename and with a value of a Soulseek.File object @@ -305,6 +306,7 @@ namespace slskd.Shares } files[file.Key] = file.Value; + InsertFile(maskedFilename: file.Key, originalFilename: file.Key, scannedAt, touchedAt: DateTime.UtcNow, file.Value); } } catch (Exception ex) @@ -332,15 +334,14 @@ namespace slskd.Shares Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } + //// potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + //foreach (var file in files) + //{ + // InsertFile(maskedFilename: file.Key, file.Value); + //} Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); - MaskedDirectories = maskedDirectories; MaskedFiles = files; State.SetValue(state => state with @@ -349,8 +350,8 @@ namespace slskd.Shares Faulted = false, Filled = true, FillProgress = 1, - Directories = MaskedDirectories.Count, - Files = MaskedFiles.Count, + Directories = CountDirectories(), + Files = CountFiles(), }); Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); @@ -460,12 +461,12 @@ namespace slskd.Shares var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); - var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; + var sql = $"SELECT * FROM filenames WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; var results = new List(); try { - using var conn = new SqliteConnection($"Data Source={Path.Combine(Program.AppDirectory, "data", "shares.db")};cache=shared"); + using var conn = new SqliteConnection(Program.ConnectionStrings.Shares); using var cmd = new SqliteCommand(sql, conn); await conn.OpenAsync(); @@ -495,31 +496,96 @@ namespace slskd.Shares } } - private void CreateTable() + private void CreateTables() { if (SQLite != null) { SQLite.Dispose(); } - SQLite = new SqliteConnection($"Data Source={Path.Combine(Program.AppDirectory, "data", "shares.db")};cache=shared"); + SQLite = new SqliteConnection(Program.ConnectionStrings.Shares); SQLite.Open(); - using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); - cmd.ExecuteNonQuery(); + using var directories = new SqliteCommand("DROP TABLE IF EXISTS directories; CREATE TABLE directories (name TEXT PRIMARY KEY);", SQLite); + directories.ExecuteNonQuery(); + + using var filenames = new SqliteCommand("DROP TABLE IF EXISTS filenames; CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename);", SQLite); + filenames.ExecuteNonQuery(); + + using var metadata = new SqliteCommand("DROP TABLE IF EXISTS files; CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, scannedAt TEXT NOT NULL, touchedAt TEXT NOT NULL, metadata TEXT NOT NULL);", SQLite); + metadata.ExecuteNonQuery(); } - private void InsertFilename(string filename) + private void InsertDirectory(string name) { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES(@filename)", SQLite); - cmd.Parameters.AddWithValue("filename", filename); + using var cmd = new SqliteCommand("INSERT INTO directories VALUES(@name) ON CONFLICT DO NOTHING;", SQLite); + cmd.Parameters.AddWithValue("name", name); cmd.ExecuteNonQuery(); } + private IEnumerable ListDirectories() + { + using var cmd = new SqliteCommand("SELECT * FROM directories;", SQLite); + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + yield return reader.GetString(0); + } + } + + private IEnumerable> ListFiles() + { + using var cmd = new SqliteCommand("SELECT maskedFilename, metadata FROM files;", SQLite); + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + var maskedFilename = reader.GetString(0); + var metadata = reader.GetString(1); + + Console.WriteLine($"fn: {maskedFilename}, metadata: {metadata}"); + + yield return KeyValuePair.Create(maskedFilename, metadata.FromJson()); + } + } + + private int CountDirectories() + { + using var cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", SQLite); + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + + private int CountFiles() + { + using var cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", SQLite); + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + + private void InsertFile(string maskedFilename, string originalFilename, DateTime scannedAt, DateTime touchedAt, File file) + { + using var filename = new SqliteCommand($"INSERT INTO filenames(maskedFilename) VALUES(@maskedFilename)", SQLite); + filename.Parameters.AddWithValue("maskedFilename", maskedFilename); + filename.ExecuteNonQuery(); + + using var metadata = new SqliteCommand("INSERT INTO files (maskedFilename, originalFilename, scannedAt, touchedAt, metadata) " + + "VALUES(@maskedFilename, @originalFilename, @scannedAt, @touchedAt, @metadata) " + + "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, scannedAt = excluded.scannedAt, touchedAt = excluded.touchedAt, metadata = excluded.metadata;", SQLite); + metadata.Parameters.AddWithValue("maskedFilename", maskedFilename); + metadata.Parameters.AddWithValue("originalFilename", originalFilename); + metadata.Parameters.AddWithValue("scannedAt", scannedAt.ToShortDateString()); + metadata.Parameters.AddWithValue("touchedAt", touchedAt.ToShortDateString()); + metadata.Parameters.AddWithValue("metadata", file.ToJson()); + metadata.ExecuteNonQuery(); + } + private void ResetCache() { - CreateTable(); - MaskedDirectories = new HashSet(); + CreateTables(); MaskedFiles = new Dictionary(); State.SetValue(state => state with { Directories = 0, Files = 0 }); } -- cgit v1.2.3 From 83e430cb034c293fb1eb35b175aab6790615a440 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 6 Sep 2022 23:43:17 -0500 Subject: add todos --- src/slskd/Shares/SharedFileCache.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index bded2a75..7f7600fd 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -512,6 +512,7 @@ namespace slskd.Shares using var filenames = new SqliteCommand("DROP TABLE IF EXISTS filenames; CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename);", SQLite); filenames.ExecuteNonQuery(); + // todo add metadata columns using var metadata = new SqliteCommand("DROP TABLE IF EXISTS files; CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, scannedAt TEXT NOT NULL, touchedAt TEXT NOT NULL, metadata TEXT NOT NULL);", SQLite); metadata.ExecuteNonQuery(); } @@ -541,6 +542,7 @@ namespace slskd.Shares while (reader.Read()) { + // todo create an instance of Soulseek.File from metadata columns var maskedFilename = reader.GetString(0); var metadata = reader.GetString(1); @@ -572,6 +574,7 @@ namespace slskd.Shares filename.Parameters.AddWithValue("maskedFilename", maskedFilename); filename.ExecuteNonQuery(); + // todo insert metadata into columns instead of json using var metadata = new SqliteCommand("INSERT INTO files (maskedFilename, originalFilename, scannedAt, touchedAt, metadata) " + "VALUES(@maskedFilename, @originalFilename, @scannedAt, @touchedAt, @metadata) " + "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, scannedAt = excluded.scannedAt, touchedAt = excluded.touchedAt, metadata = excluded.metadata;", SQLite); -- cgit v1.2.3 From 1068fb5acf97cd47d707d5f28b0cc3c73b389fdd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 09:01:06 -0500 Subject: add SqliteConnectionExtensions --- src/slskd/Common/SqliteConnectionExtensions.cs | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/slskd/Common/SqliteConnectionExtensions.cs (limited to 'src') diff --git a/src/slskd/Common/SqliteConnectionExtensions.cs b/src/slskd/Common/SqliteConnectionExtensions.cs new file mode 100644 index 00000000..3944c10b --- /dev/null +++ b/src/slskd/Common/SqliteConnectionExtensions.cs @@ -0,0 +1,32 @@ +// +// 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 +{ + using System; + using Microsoft.Data.Sqlite; + + public static class SqliteConnectionExtensions + { + public static int ExecuteNonQuery(this SqliteConnection conn, string query, Action action = null) + { + using var cmd = new SqliteCommand(query, conn); + action?.Invoke(cmd); + return cmd.ExecuteNonQuery(); + } + } +} -- cgit v1.2.3 From e3a189f3bf17a868e65b61754378f0af0db4fd46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 09:01:25 -0500 Subject: refactor list and browse to use iterators --- src/slskd/Shares/SharedFileCache.cs | 147 ++++++++++++++++-------------------- 1 file changed, 67 insertions(+), 80 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 7f7600fd..bea18809 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -20,7 +20,6 @@ using System.IO; namespace slskd.Shares { using System; - using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -116,45 +115,17 @@ namespace slskd.Shares { if (State.CurrentValue.Filling) { - return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; + yield return new Directory("Scanning shares, please check back in a few minutes."); } - return Enumerable.Empty(); + yield break; } - var directories = new ConcurrentDictionary(); - - // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if - // missing, files that are nested within directories which contain only directories (no files) are displayed as being - // 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 ListDirectories()) - { - directories.TryAdd(directory, new Directory(directory)); - } - - var groups = ListFiles() - .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Directory(g.Key, g.Select(g => - { - var f = g.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. - f.Size, - f.Extension, - f.Attributes); - }))); - - // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. - // entries with no files will remain untouched. - foreach (var group in groups) + foreach (var directory in ListDirectories().OrderBy(d => d)) { - directories.AddOrUpdate(group.Name, group, (_, _) => group); + var files = ListFiles(directory); + yield return new Directory(directory, files); } - - return directories.Values.OrderBy(f => f.Name); } /// @@ -306,7 +277,7 @@ namespace slskd.Shares } files[file.Key] = file.Value; - InsertFile(maskedFilename: file.Key, originalFilename: file.Key, scannedAt, touchedAt: DateTime.UtcNow, file.Value); + InsertFile(maskedFilename: file.Key, originalFilename: file.Key, scannedAt, file.Value); } } catch (Exception ex) @@ -385,17 +356,7 @@ namespace slskd.Shares return null; } - var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => - { - var f = kvp.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), - f.Size, - f.Extension, - f.Attributes); - }); - + var files = ListFiles(directory); return new Directory(directory, files); } @@ -506,22 +467,23 @@ namespace slskd.Shares SQLite = new SqliteConnection(Program.ConnectionStrings.Shares); SQLite.Open(); - using var directories = new SqliteCommand("DROP TABLE IF EXISTS directories; CREATE TABLE directories (name TEXT PRIMARY KEY);", SQLite); - directories.ExecuteNonQuery(); + SQLite.ExecuteNonQuery("DROP TABLE IF EXISTS directories; CREATE TABLE directories (name TEXT PRIMARY KEY);"); - using var filenames = new SqliteCommand("DROP TABLE IF EXISTS filenames; CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename);", SQLite); - filenames.ExecuteNonQuery(); + SQLite.ExecuteNonQuery("DROP TABLE IF EXISTS filenames; CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename);"); - // todo add metadata columns - using var metadata = new SqliteCommand("DROP TABLE IF EXISTS files; CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, scannedAt TEXT NOT NULL, touchedAt TEXT NOT NULL, metadata TEXT NOT NULL);", SQLite); - metadata.ExecuteNonQuery(); + SQLite.ExecuteNonQuery("DROP TABLE IF EXISTS 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);"); + + SQLite.ExecuteNonQuery("DROP TABLE IF EXISTS excluded; CREATE TABLE excluded (originalFilename TEXT PRIMARY KEY);"); } private void InsertDirectory(string name) { - using var cmd = new SqliteCommand("INSERT INTO directories VALUES(@name) ON CONFLICT DO NOTHING;", SQLite); - cmd.Parameters.AddWithValue("name", name); - cmd.ExecuteNonQuery(); + SQLite.ExecuteNonQuery("INSERT INTO directories VALUES(@name) ON CONFLICT DO NOTHING;", cmd => + { + cmd.Parameters.AddWithValue("name", name); + }); } private IEnumerable ListDirectories() @@ -535,20 +497,42 @@ namespace slskd.Shares } } - private IEnumerable> ListFiles() + private IEnumerable ListFiles(string directory = null) { - using var cmd = new SqliteCommand("SELECT maskedFilename, metadata FROM files;", SQLite); - var reader = cmd.ExecuteReader(); + SqliteCommand cmd = default; - while (reader.Read()) + try { - // todo create an instance of Soulseek.File from metadata columns - var maskedFilename = reader.GetString(0); - var metadata = reader.GetString(1); + if (string.IsNullOrEmpty(directory)) + { + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", SQLite); + } + else + { + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match", SQLite); + cmd.Parameters.AddWithValue("match", directory + '%'); + } + + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + var filename = reader.GetString(0); + var code = reader.GetInt32(1); + var size = reader.GetInt64(2); + var extension = reader.GetString(3); + var attributeJson = reader.GetString(4); - Console.WriteLine($"fn: {maskedFilename}, metadata: {metadata}"); + var attributeList = attributeJson.FromJson>(); - yield return KeyValuePair.Create(maskedFilename, metadata.FromJson()); + var file = new File(code, filename: Path.GetFileName(filename), size, extension, attributeList); + + yield return file; + } + } + finally + { + cmd?.Dispose(); } } @@ -568,22 +552,25 @@ namespace slskd.Shares return reader.GetInt32(0); } - private void InsertFile(string maskedFilename, string originalFilename, DateTime scannedAt, DateTime touchedAt, File file) + private void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file) { - using var filename = new SqliteCommand($"INSERT INTO filenames(maskedFilename) VALUES(@maskedFilename)", SQLite); - filename.Parameters.AddWithValue("maskedFilename", maskedFilename); - filename.ExecuteNonQuery(); - - // todo insert metadata into columns instead of json - using var metadata = new SqliteCommand("INSERT INTO files (maskedFilename, originalFilename, scannedAt, touchedAt, metadata) " + - "VALUES(@maskedFilename, @originalFilename, @scannedAt, @touchedAt, @metadata) " + - "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, scannedAt = excluded.scannedAt, touchedAt = excluded.touchedAt, metadata = excluded.metadata;", SQLite); - metadata.Parameters.AddWithValue("maskedFilename", maskedFilename); - metadata.Parameters.AddWithValue("originalFilename", originalFilename); - metadata.Parameters.AddWithValue("scannedAt", scannedAt.ToShortDateString()); - metadata.Parameters.AddWithValue("touchedAt", touchedAt.ToShortDateString()); - metadata.Parameters.AddWithValue("metadata", file.ToJson()); - metadata.ExecuteNonQuery(); + SQLite.ExecuteNonQuery("INSERT INTO filenames(maskedFilename) VALUES(@maskedFilename);", cmd => + { + cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); + }); + + SQLite.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson) " + + "VALUES(@maskedFilename, @originalFilename, @size, @touchedAt, @code, @extension, @attributeJson) " + + "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, size = excluded.size, touchedAt = excluded.touchedAt, code = excluded.code, extension = excluded.extension, attributeJson = excluded.attributeJson;", cmd => + { + cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); + cmd.Parameters.AddWithValue("originalFilename", originalFilename); + cmd.Parameters.AddWithValue("size", file.Size); + cmd.Parameters.AddWithValue("touchedAt", touchedAt.ToLongDateString()); + cmd.Parameters.AddWithValue("code", file.Code); + cmd.Parameters.AddWithValue("extension", file.Extension); + cmd.Parameters.AddWithValue("attributeJson", file.Attributes.ToJson()); + }); } private void ResetCache() -- cgit v1.2.3 From dcee8c07f9a76e4299b59e81e80a07f6df126ee3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 21:39:25 -0500 Subject: wip --- src/slskd/Application.cs | 42 +++++-- src/slskd/Shares/IShareService.cs | 2 + src/slskd/Shares/ShareService.cs | 17 ++- src/slskd/Shares/SharedFileCache.cs | 241 ++++++++++++++++++++---------------- src/slskd/slskd.csproj | 2 +- 5 files changed, 184 insertions(+), 120 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e4d47bb1..6c6ee475 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -369,14 +369,22 @@ namespace slskd _ = CheckVersionAsync(); } - if (OptionsAtStartup.Flags.NoShareScan) - { - Log.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); - } - else - { - _ = Shares.StartScanAsync(); - } + //if (OptionsAtStartup.Flags.NoShareScan) + //{ + // Log.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); + //} + //else + //{ + // _ = Shares.StartScanAsync(); + //} + + Shares.LoadFromDisk(); + Log.Information("Shares loaded from disk"); + + Log.Information("Caching browse response..."); + var browse = new BrowseResponse(await Shares.BrowseAsync()).ToByteArray(); + System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, "browse.cache"), browse); + Log.Information("Browse response cached."); if (OptionsAtStartup.Flags.NoConnect) { @@ -417,7 +425,21 @@ namespace slskd var sw = new Stopwatch(); sw.Start(); - var directories = await Shares.BrowseAsync(); + BrowseResponse response = default; + + var cacheFilename = Path.Combine(Program.DataDirectory, "browse.cache"); + var cacheFileInfo = new System.IO.FileInfo(cacheFilename); + + if (cacheFileInfo.Exists) + { + var stream = new System.IO.FileStream(cacheFilename, FileMode.Open, FileAccess.Read); + response = new RawBrowseResponse(cacheFileInfo.Length, stream); + } + else + { + var directories = await Shares.BrowseAsync(); + response = new BrowseResponse(directories); + } sw.Stop(); @@ -425,7 +447,7 @@ namespace slskd Metrics.Browse.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); Metrics.Browse.ResponsesSent.Inc(1); - return new BrowseResponse(directories); + return response; } catch (Exception ex) { diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index a2eeed92..42f83a51 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -75,5 +75,7 @@ namespace slskd.Shares /// The operation context. /// Thrown when a scan is already in progress. Task StartScanAsync(); + + void LoadFromDisk(); } } diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 60b69967..2eb8dfe3 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -142,16 +142,21 @@ namespace slskd.Shares /// /// The query for which to search. /// The matching files. - public async Task> SearchAsync(SearchQuery query) + public Task> SearchAsync(SearchQuery query) { - var results = await Cache.SearchAsync(query); + var results = Cache.Search(query); - return results.Select(r => new File( + return Task.FromResult(results.Select(r => new File( r.Code, r.Filename.NormalizePath(), r.Size, r.Extension, - r.Attributes)); + r.Attributes))); + } + + public void LoadFromDisk() + { + Cache.Load(); } /// @@ -160,7 +165,9 @@ namespace slskd.Shares /// The operation context. /// Thrown when a scan is already in progress. public Task StartScanAsync() - => Cache.FillAsync(Shares, FilterRegexes); + { + return Cache.FillAsync(Shares, FilterRegexes); + } private void Configure(Options options) { diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index bea18809..355cef97 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -46,6 +46,8 @@ namespace slskd.Shares /// The contents of the cache. IEnumerable Browse(); + void Load(); + /// /// Scans the configured shares and fills the cache. /// @@ -75,7 +77,7 @@ namespace slskd.Shares /// /// The query for which to search. /// The matching files. - Task> SearchAsync(SearchQuery query); + IEnumerable Search(SearchQuery query); } /// @@ -98,13 +100,19 @@ namespace slskd.Shares public IStateMonitor StateMonitor => State; private ILogger Log { get; } = Serilog.Log.ForContext(); - private Dictionary MaskedFiles { get; set; } private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } - private SqliteConnection SQLite { get; set; } + //private SqliteConnection SQLite { get; set; } private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + private SqliteConnection GetConnection() + { + var conn = new SqliteConnection(Program.ConnectionStrings.Shares); + conn.Open(); + return conn; + } + /// /// Returns the contents of the cache. /// @@ -115,17 +123,68 @@ namespace slskd.Shares { if (State.CurrentValue.Filling) { - yield return new Directory("Scanning shares, please check back in a few minutes."); + return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; } - yield break; + return Enumerable.Empty(); } - foreach (var directory in ListDirectories().OrderBy(d => d)) + //foreach (var directory in ListDirectories().OrderBy(d => d)) + //{ + // var files = ListFiles(directory); + // yield return new Directory(directory, files); + //} + + var files = new List(); + + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", conn); + var reader = cmd.ExecuteReader(); + + while (reader.Read()) { - var files = ListFiles(directory); - yield return new Directory(directory, files); + var filename = reader.GetString(0); + var code = reader.GetInt32(1); + var size = reader.GetInt64(2); + var extension = reader.GetString(3); + var attributeJson = reader.GetString(4); + + var attributeList = attributeJson.FromJson>(); + + var file = new File(code, filename: Path.GetFileName(filename), size, extension, attributeList); + + files.Add(file); } + + Console.WriteLine($"Fetched {files.Count} files, slicing and dicing..."); + + var directories = files + .GroupBy(file => Path.GetDirectoryName(file.Filename)) + .Select(group => new Directory(group.Key, group.Select(f => + { + return new File( + f.Code, + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. + f.Size, + f.Extension, + f.Attributes); + }))); + + Console.WriteLine($"Sliced and diced, returning..."); + return directories; + } + + public void Load() + { + State.SetValue(state => state with + { + Filling = false, + Faulted = false, + Filled = true, + FillProgress = 1, + Directories = CountDirectories(), + Files = CountFiles(), + }); } /// @@ -158,7 +217,6 @@ namespace slskd.Shares ResetCache(); - var scannedAt = DateTime.UtcNow; var sw = new Stopwatch(); var swSnapshot = 0L; sw.Start(); @@ -215,10 +273,10 @@ namespace slskd.Shares Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; - var files = new Dictionary(); var maskedDirectories = new HashSet(); - var current = 0L; - var filtered = 0L; + var current = 0; + var cached = 0; + var filtered = 0; foreach (var directory in unmaskedDirectories) { @@ -230,8 +288,8 @@ namespace slskd.Shares continue; } - var addedFiles = 0L; - var filteredFiles = 0L; + var addedFiles = 0; + var filteredFiles = 0; var share = Shares.First(share => directory.StartsWith(share.LocalPath)); @@ -249,35 +307,30 @@ namespace slskd.Shares AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, IgnoreInaccessible = true, RecurseSubdirectories = false, - }) - .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) - .ToDictionary(file => file.Filename, file => file); + }); - addedFiles = newFiles.Count; + addedFiles = newFiles.Count(); // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var file in newFiles) + foreach (var originalFilename in newFiles) { - if (filters.Any(filter => filter.IsMatch(file.Key))) + var info = new FileInfo(originalFilename); + var file = SoulseekFileFactory.Create(originalFilename, maskedFilename: originalFilename.ReplaceFirst(share.LocalPath, share.RemotePath)); + + if (filters.Any(filter => filter.IsMatch(originalFilename))) { filteredFiles++; continue; } - if (Path.DirectorySeparatorChar == '/' && file.Value.Filename.Contains('\\')) + if (Path.DirectorySeparatorChar == '/' && file.Filename.Contains('\\')) { - Log.Warning("Filename {Filename} contains one or more backslashes, which are not currently supported. This file will not be shared.", file.Value.Filename); + Log.Warning("Filename {Filename} contains one or more backslashes, which are not currently supported. This file will not be shared.", file.Filename); continue; } - if (files.ContainsKey(file.Key)) - { - Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); - } - - files[file.Key] = file.Value; - InsertFile(maskedFilename: file.Key, originalFilename: file.Key, scannedAt, file.Value); + InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file); } } catch (Exception ex) @@ -288,12 +341,13 @@ namespace slskd.Shares current++; filtered += filteredFiles; + cached += addedFiles; Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles); try { - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); } catch (Exception ex) { @@ -302,18 +356,10 @@ namespace slskd.Shares } } - Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; - //// potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - //foreach (var file in files) - //{ - // InsertFile(maskedFilename: file.Key, file.Value); - //} - - Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); - - MaskedFiles = files; + Log.Debug("Inserted {Files} records in {Elapsed}ms", cached, sw.ElapsedMilliseconds - swSnapshot); State.SetValue(state => state with { @@ -325,7 +371,7 @@ namespace slskd.Shares Files = CountFiles(), }); - Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {cached}"); } catch (Exception ex) { @@ -368,35 +414,19 @@ namespace slskd.Shares /// The unmasked filename. public string Resolve(string filename) { - // ensure this is a tracked file - if (!MaskedFiles.TryGetValue(filename, out _)) - { - return null; - } - - var resolved = filename; - - // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a - // file. split the requested filename so we can examine the first two segments - var parts = filename.Split(new[] { '/', '\\' }); + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn); + cmd.Parameters.AddWithValue("maskedFilename", filename); - if (parts.Length < 2) - { - Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); - return null; - } - - // find the share with a matching mask and alias/local directory - var share = Shares.FirstOrDefault(share => share.Alias == parts[0]); + var reader = cmd.ExecuteReader(); - if (share == default) + if (!reader.Read()) { - Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from alias '{Alias}'", filename, parts[0]); + Log.Warning("Failed to resolve shared file {Filename}", filename); return null; } - resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); - + var resolved = reader.GetString(0); Log.Debug($"Resolved requested shared file {filename} to {resolved}"); return resolved; } @@ -406,7 +436,7 @@ namespace slskd.Shares /// /// The query for which to search. /// The matching files. - public async Task> SearchAsync(SearchQuery query) + public IEnumerable Search(SearchQuery query) { if (!State.CurrentValue.Filled) { @@ -422,65 +452,62 @@ namespace slskd.Shares var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); - var sql = $"SELECT * FROM filenames WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; - var results = new List(); + var sql = $"SELECT files.maskedFilename, files.code, files.size, files.extension, files.attributeJson FROM filenames " + + "INNER JOIN files ON filenames.maskedFilename = files.maskedFilename " + + $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}';"; + + var results = new List(); + SqliteDataReader reader = default; try { - using var conn = new SqliteConnection(Program.ConnectionStrings.Shares); + using var conn = GetConnection(); using var cmd = new SqliteCommand(sql, conn); - await conn.OpenAsync(); - - var reader = await cmd.ExecuteReaderAsync(); + reader = cmd.ExecuteReader(); while (reader.Read()) { - results.Add(reader.GetString(0)); + var filename = reader.GetString(0); + var code = reader.GetInt32(1); + var size = reader.GetInt64(2); + var extension = reader.GetString(3); + var attributeJson = reader.GetString(4); + + var attributeList = attributeJson.FromJson>(); + + var file = new File(code, filename, size, extension, attributeList); + results.Add(file); } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); - return Enumerable.Empty(); - } - try - { - return results - .Select(r => MaskedFiles[r]) - .ToList(); + return results; } catch (Exception ex) { - Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); + Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); return Enumerable.Empty(); } } private void CreateTables() { - if (SQLite != null) - { - SQLite.Dispose(); - } - - SQLite = new SqliteConnection(Program.ConnectionStrings.Shares); - SQLite.Open(); + using var conn = GetConnection(); - SQLite.ExecuteNonQuery("DROP TABLE IF EXISTS directories; CREATE TABLE directories (name TEXT PRIMARY KEY);"); + conn.ExecuteNonQuery("DROP TABLE IF EXISTS directories; CREATE TABLE directories (name TEXT PRIMARY KEY);"); - SQLite.ExecuteNonQuery("DROP TABLE IF EXISTS filenames; CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename);"); + conn.ExecuteNonQuery("DROP TABLE IF EXISTS filenames; CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename);"); - SQLite.ExecuteNonQuery("DROP TABLE IF EXISTS files; CREATE TABLE files " + + conn.ExecuteNonQuery("DROP TABLE IF EXISTS 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);"); - SQLite.ExecuteNonQuery("DROP TABLE IF EXISTS excluded; CREATE TABLE excluded (originalFilename TEXT PRIMARY KEY);"); + conn.ExecuteNonQuery("DROP TABLE IF EXISTS excluded; CREATE TABLE excluded (originalFilename TEXT PRIMARY KEY);"); } private void InsertDirectory(string name) { - SQLite.ExecuteNonQuery("INSERT INTO directories VALUES(@name) ON CONFLICT DO NOTHING;", cmd => + using var conn = GetConnection(); + + conn.ExecuteNonQuery("INSERT INTO directories VALUES(@name) ON CONFLICT DO NOTHING;", cmd => { cmd.Parameters.AddWithValue("name", name); }); @@ -488,7 +515,9 @@ namespace slskd.Shares private IEnumerable ListDirectories() { - using var cmd = new SqliteCommand("SELECT * FROM directories;", SQLite); + using var conn = GetConnection(); + + using var cmd = new SqliteCommand("SELECT * FROM directories;", conn); var reader = cmd.ExecuteReader(); while (reader.Read()) @@ -500,16 +529,17 @@ namespace slskd.Shares private IEnumerable ListFiles(string directory = null) { SqliteCommand cmd = default; + using var conn = GetConnection(); try { if (string.IsNullOrEmpty(directory)) { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", SQLite); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", conn); } else { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match", SQLite); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match", conn); cmd.Parameters.AddWithValue("match", directory + '%'); } @@ -538,7 +568,8 @@ namespace slskd.Shares private int CountDirectories() { - using var cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", SQLite); + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn); var reader = cmd.ExecuteReader(); reader.Read(); return reader.GetInt32(0); @@ -546,7 +577,8 @@ namespace slskd.Shares private int CountFiles() { - using var cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", SQLite); + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn); var reader = cmd.ExecuteReader(); reader.Read(); return reader.GetInt32(0); @@ -554,12 +586,14 @@ namespace slskd.Shares private void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file) { - SQLite.ExecuteNonQuery("INSERT INTO filenames(maskedFilename) VALUES(@maskedFilename);", cmd => + using var conn = GetConnection(); + + conn.ExecuteNonQuery("INSERT INTO filenames(maskedFilename) VALUES(@maskedFilename);", cmd => { cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); }); - SQLite.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson) " + + conn.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson) " + "VALUES(@maskedFilename, @originalFilename, @size, @touchedAt, @code, @extension, @attributeJson) " + "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, size = excluded.size, touchedAt = excluded.touchedAt, code = excluded.code, extension = excluded.extension, attributeJson = excluded.attributeJson;", cmd => { @@ -576,7 +610,6 @@ namespace slskd.Shares private void ResetCache() { CreateTables(); - MaskedFiles = new Dictionary(); State.SetValue(state => state with { Directories = 0, Files = 0 }); } } diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index bfb2f3f0..4a8622bc 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 6198899be5c2654d80766ce6a1c0451c10ac0a50 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 22:04:17 -0500 Subject: fix browse --- src/slskd/Shares/SharedFileCache.cs | 41 +++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 355cef97..39fc4b20 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -20,6 +20,7 @@ using System.IO; namespace slskd.Shares { using System; + using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -129,16 +130,22 @@ namespace slskd.Shares return Enumerable.Empty(); } - //foreach (var directory in ListDirectories().OrderBy(d => d)) - //{ - // var files = ListFiles(directory); - // yield return new Directory(directory, files); - //} + var directories = new ConcurrentDictionary(); + + // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if + // missing, files that are nested within directories which contain only directories (no files) are displayed as being + // 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 ListDirectories()) + { + directories.TryAdd(directory, new Directory(directory)); + } var files = new List(); using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", conn); + using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); var reader = cmd.ExecuteReader(); while (reader.Read()) @@ -151,14 +158,12 @@ namespace slskd.Shares var attributeList = attributeJson.FromJson>(); - var file = new File(code, filename: Path.GetFileName(filename), size, extension, attributeList); + var file = new File(code, filename, size, extension, attributeList); files.Add(file); } - Console.WriteLine($"Fetched {files.Count} files, slicing and dicing..."); - - var directories = files + var groups = files .GroupBy(file => Path.GetDirectoryName(file.Filename)) .Select(group => new Directory(group.Key, group.Select(f => { @@ -170,8 +175,14 @@ namespace slskd.Shares f.Attributes); }))); - Console.WriteLine($"Sliced and diced, returning..."); - return directories; + // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. + // entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values; } public void Load() @@ -517,7 +528,7 @@ namespace slskd.Shares { using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT * FROM directories;", conn); + using var cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); var reader = cmd.ExecuteReader(); while (reader.Read()) @@ -535,11 +546,11 @@ namespace slskd.Shares { if (string.IsNullOrEmpty(directory)) { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", conn); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); } else { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match", conn); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ORDER BY maskedFilename ASC;", conn); cmd.Parameters.AddWithValue("match", directory + '%'); } -- cgit v1.2.3 From f8d129bb570af056e9646582089895ad7f775faa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 22:21:19 -0500 Subject: add Filenames --- src/slskd/Core/Filenames.cs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/slskd/Core/Filenames.cs (limited to 'src') diff --git a/src/slskd/Core/Filenames.cs b/src/slskd/Core/Filenames.cs new file mode 100644 index 00000000..0fc55fc5 --- /dev/null +++ b/src/slskd/Core/Filenames.cs @@ -0,0 +1,30 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Application files. + /// + public static class Filenames + { + public static readonly string TransfersDb = "transfers.db"; + public static readonly string SharesDb = "shares.db"; + public static readonly string SearchDb = "search.db"; + public static readonly string BrowseCache = "browse.cache"; + } +} -- cgit v1.2.3 From 8b1e4a50079afd5e7b37b264e7b2f72135cd9530 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 22:21:41 -0500 Subject: use Filenames --- src/slskd/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 371f60bd..f4e59456 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -260,9 +260,9 @@ namespace slskd 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={Path.Combine(DataDirectory, "shares.db")};Cache=shared", + Search = $"Data Source={Path.Combine(DataDirectory, Filenames.SearchDb)};Cache=shared;Pooling=True;", + Transfers = $"Data Source={Path.Combine(DataDirectory, Filenames.TransfersDb)};Cache=shared;Pooling=True;", + Shares = $"Data Source={Path.Combine(DataDirectory, Filenames.SharesDb)};Cache=shared", }; DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml"); -- cgit v1.2.3 From de66bee3e4b4ef168bd320c3ea1135906e223b2c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 23:26:27 -0500 Subject: add TryLoadFromDiskAsync() --- src/slskd/Shares/IShareService.cs | 8 ++++++-- src/slskd/Shares/ShareService.cs | 14 +++++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 42f83a51..962d4c1e 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -76,6 +76,10 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. Task StartScanAsync(); - void LoadFromDisk(); + /// + /// Attempt to load shares from disk. + /// + /// A value indicating whether shares were loaded. + Task TryLoadFromDiskAsync(); } -} +} \ No newline at end of file diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 2eb8dfe3..244d2f9b 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -154,11 +154,6 @@ namespace slskd.Shares r.Attributes))); } - public void LoadFromDisk() - { - Cache.Load(); - } - /// /// Starts a scan of the configured shares. /// @@ -169,6 +164,15 @@ namespace slskd.Shares return Cache.FillAsync(Shares, FilterRegexes); } + /// + /// Attempt to load shares from disk. + /// + /// A value indicating whether shares were loaded. + public Task TryLoadFromDiskAsync() + { + return Task.FromResult(Cache.TryLoad()); + } + private void Configure(Options options) { SyncRoot.Wait(); -- cgit v1.2.3 From 425991e9fcb3519eaff0a0411e0777e6e74c1503 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 23:27:31 -0500 Subject: check tables in TryLoad --- src/slskd/Shares/SharedFileCache.cs | 76 +++++++++++++++++++++++++++++++------ 1 file changed, 65 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 39fc4b20..7cbea3fd 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -47,7 +47,11 @@ namespace slskd.Shares /// The contents of the cache. IEnumerable Browse(); - void Load(); + /// + /// Attempts to load the cache from disk. + /// + /// A value indicating whether the load was successful. + bool TryLoad(); /// /// Scans the configured shares and fills the cache. @@ -185,17 +189,36 @@ namespace slskd.Shares return directories.Values; } - public void Load() + /// + /// Attempts to load the cache from disk. + /// + /// A value indicating whether the load was successful. + public bool TryLoad() { - State.SetValue(state => state with + try { - Filling = false, - Faulted = false, - Filled = true, - FillProgress = 1, - Directories = CountDirectories(), - Files = CountFiles(), - }); + if (TableExists("directories") && TableExists("filenames") && TableExists("files") && TableExists("exclusions")) + { + State.SetValue(state => state with + { + Filling = false, + Faulted = false, + Filled = true, + FillProgress = 1, + Directories = CountDirectories(), + Files = CountFiles(), + }); + + return true; + } + + return false; + } + catch (Exception ex) + { + Log.Debug(ex, "Error loading shared file cache: {Message}", ex.Message); + return false; + } } /// @@ -511,7 +534,7 @@ namespace slskd.Shares "(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);"); - conn.ExecuteNonQuery("DROP TABLE IF EXISTS excluded; CREATE TABLE excluded (originalFilename TEXT PRIMARY KEY);"); + conn.ExecuteNonQuery("DROP TABLE IF EXISTS exclusions; CREATE TABLE exclusions (originalFilename TEXT PRIMARY KEY);"); } private void InsertDirectory(string name) @@ -618,9 +641,40 @@ namespace slskd.Shares }); } + private bool TableExists(string table) + { + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT name from sqlite_master WHERE type = 'table' AND name = @table;", conn); + cmd.Parameters.AddWithValue("table", table); + var reader = cmd.ExecuteReader(); + + if (reader.Read()) + { + var fetchedTable = reader.GetString(0); + Console.WriteLine($"Fetched: {fetchedTable}"); + return table == fetchedTable; + } + else + { + Console.WriteLine("Read() was false"); + } + + return false; + } + private void ResetCache() { CreateTables(); + + try + { + System.IO.File.Delete(Path.Combine(Program.DataDirectory, Filenames.BrowseCache)); + } + catch (FileNotFoundException) + { + // noop + } + State.SetValue(state => state with { Directories = 0, Files = 0 }); } } -- cgit v1.2.3 From 2729bc7c6315bf1555a8761de94134e5171d4014 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Sep 2022 23:29:07 -0500 Subject: load cache on start, or force scan. cache first browse response --- src/slskd/Application.cs | 60 +++++++++++++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 6c6ee475..07cf5dbd 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -369,22 +369,23 @@ namespace slskd _ = CheckVersionAsync(); } - //if (OptionsAtStartup.Flags.NoShareScan) - //{ - // Log.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); - //} - //else - //{ - // _ = Shares.StartScanAsync(); - //} - - Shares.LoadFromDisk(); - Log.Information("Shares loaded from disk"); - - Log.Information("Caching browse response..."); - var browse = new BrowseResponse(await Shares.BrowseAsync()).ToByteArray(); - System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, "browse.cache"), browse); - Log.Information("Browse response cached."); + if (await Shares.TryLoadFromDiskAsync()) + { + Log.Information("Loaded share cache from disk"); + } + else + { + Log.Warning("Failed to load share cache from disk. A share scan is required."); + + if (OptionsAtStartup.Flags.NoShareScan) + { + Log.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); + } + else + { + _ = Shares.StartScanAsync(); + } + } if (OptionsAtStartup.Flags.NoConnect) { @@ -427,20 +428,33 @@ namespace slskd BrowseResponse response = default; - var cacheFilename = Path.Combine(Program.DataDirectory, "browse.cache"); + var cacheFilename = Path.Combine(Program.DataDirectory, Filenames.BrowseCache); var cacheFileInfo = new System.IO.FileInfo(cacheFilename); - if (cacheFileInfo.Exists) - { - var stream = new System.IO.FileStream(cacheFilename, FileMode.Open, FileAccess.Read); - response = new RawBrowseResponse(cacheFileInfo.Length, stream); - } - else + if (!cacheFileInfo.Exists) { + Log.Warning("Browse response not cached. Rebuilding..."); + var directories = await Shares.BrowseAsync(); response = new BrowseResponse(directories); + + Log.Information("Caching browse response..."); + System.IO.File.WriteAllBytes(cacheFilename, response.ToByteArray()); + Log.Information("Browse response cached successfully"); } + cacheFileInfo = new System.IO.FileInfo(cacheFilename); + + if (!cacheFileInfo.Exists) + { + throw new IOException("Unable to access recently written browse cache; is the file still open?"); + } + + var stream = new System.IO.FileStream(cacheFilename, FileMode.Open, FileAccess.Read); + response = new RawBrowseResponse(cacheFileInfo.Length, stream); + + Log.Information("Returned cached browse response for {User}", username); + sw.Stop(); Metrics.Browse.ResponseLatency.Observe(sw.ElapsedMilliseconds); -- cgit v1.2.3 From afe8d127fc24d7814bc236fdaf916a5544f42cc2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 16:49:38 -0500 Subject: bump Soulseek.NET again --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 4a8622bc..f35a6485 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 67af06ed956f2943df7f27a9c56555be7e359786 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 18:37:03 -0500 Subject: spacing --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 7cbea3fd..427a34db 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -622,7 +622,7 @@ namespace slskd.Shares { using var conn = GetConnection(); - conn.ExecuteNonQuery("INSERT INTO filenames(maskedFilename) VALUES(@maskedFilename);", cmd => + conn.ExecuteNonQuery("INSERT INTO filenames (maskedFilename) VALUES(@maskedFilename);", cmd => { cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); }); -- cgit v1.2.3 From a2763ea52ce479064f78683a097537f56c32eb64 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 20:38:41 -0500 Subject: remove order by --- src/slskd/Shares/SharedFileCache.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 427a34db..730989f7 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -149,7 +149,7 @@ namespace slskd.Shares var files = new List(); using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); + using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", conn); var reader = cmd.ExecuteReader(); while (reader.Read()) @@ -551,7 +551,7 @@ namespace slskd.Shares { using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); + using var cmd = new SqliteCommand("SELECT name FROM directories;", conn); var reader = cmd.ExecuteReader(); while (reader.Read()) @@ -569,11 +569,11 @@ namespace slskd.Shares { if (string.IsNullOrEmpty(directory)) { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", conn); } else { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ORDER BY maskedFilename ASC;", conn); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match;", conn); cmd.Parameters.AddWithValue("match", directory + '%'); } @@ -622,11 +622,6 @@ namespace slskd.Shares { using var conn = GetConnection(); - conn.ExecuteNonQuery("INSERT INTO filenames (maskedFilename) VALUES(@maskedFilename);", cmd => - { - cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); - }); - conn.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson) " + "VALUES(@maskedFilename, @originalFilename, @size, @touchedAt, @code, @extension, @attributeJson) " + "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, size = excluded.size, touchedAt = excluded.touchedAt, code = excluded.code, extension = excluded.extension, attributeJson = excluded.attributeJson;", cmd => @@ -639,6 +634,11 @@ namespace slskd.Shares cmd.Parameters.AddWithValue("extension", file.Extension); cmd.Parameters.AddWithValue("attributeJson", file.Attributes.ToJson()); }); + + conn.ExecuteNonQuery("INSERT INTO filenames (maskedFilename) VALUES(@maskedFilename);", cmd => + { + cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); + }); } private bool TableExists(string table) -- cgit v1.2.3 From b65dcc85a19fd178e6e7aa38053287e762b1926c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 20:43:12 -0500 Subject: clean up --- src/slskd/Shares/SharedFileCache.cs | 205 ++++++++++++++++++------------------ 1 file changed, 102 insertions(+), 103 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 730989f7..ed55fe2a 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -47,12 +47,6 @@ namespace slskd.Shares /// The contents of the cache. IEnumerable Browse(); - /// - /// Attempts to load the cache from disk. - /// - /// A value indicating whether the load was successful. - bool TryLoad(); - /// /// Scans the configured shares and fills the cache. /// @@ -83,6 +77,12 @@ namespace slskd.Shares /// The query for which to search. /// The matching files. IEnumerable Search(SearchQuery query); + + /// + /// Attempts to load the cache from disk. + /// + /// A value indicating whether the load was successful. + bool TryLoad(); } /// @@ -107,17 +107,9 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext(); private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } - //private SqliteConnection SQLite { get; set; } private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - private SqliteConnection GetConnection() - { - var conn = new SqliteConnection(Program.ConnectionStrings.Shares); - conn.Open(); - return conn; - } - /// /// Returns the contents of the cache. /// @@ -189,38 +181,6 @@ namespace slskd.Shares return directories.Values; } - /// - /// Attempts to load the cache from disk. - /// - /// A value indicating whether the load was successful. - public bool TryLoad() - { - try - { - if (TableExists("directories") && TableExists("filenames") && TableExists("files") && TableExists("exclusions")) - { - State.SetValue(state => state with - { - Filling = false, - Faulted = false, - Filled = true, - FillProgress = 1, - Directories = CountDirectories(), - Files = CountFiles(), - }); - - return true; - } - - return false; - } - catch (Exception ex) - { - Log.Debug(ex, "Error loading shared file cache: {Message}", ex.Message); - return false; - } - } - /// /// Scans the configured shares and fills the cache. /// @@ -273,9 +233,9 @@ namespace slskd.Shares Log.Debug("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; - // derive a list of all directories from all shares - // skip hidden and system directories, as well as anything that can't be accessed due to security restrictions. - // it's necessary to enumerate these directories up front so we can deduplicate directories and apply exclusions + // derive a list of all directories from all shares skip hidden and system directories, as well as anything that + // can't be accessed due to security restrictions. it's necessary to enumerate these directories up front so we + // can deduplicate directories and apply exclusions var unmaskedDirectories = Shares .SelectMany(share => { @@ -334,8 +294,8 @@ namespace slskd.Shares // filename and with a value of a Soulseek.File object try { - // enumerate files in this directory only (no subdirectories) - // exclude hidden and system files and anything that can't be accessed due to security restrictions + // enumerate files in this directory only (no subdirectories) exclude hidden and system files and anything + // that can't be accessed due to security restrictions var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions() { AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, @@ -522,6 +482,56 @@ namespace slskd.Shares } } + /// + /// Attempts to load the cache from disk. + /// + /// A value indicating whether the load was successful. + public bool TryLoad() + { + try + { + if (TableExists("directories") && TableExists("filenames") && TableExists("files") && TableExists("exclusions")) + { + State.SetValue(state => state with + { + Filling = false, + Faulted = false, + Filled = true, + FillProgress = 1, + Directories = CountDirectories(), + Files = CountFiles(), + }); + + return true; + } + + return false; + } + catch (Exception ex) + { + Log.Debug(ex, "Error loading shared file cache: {Message}", ex.Message); + return false; + } + } + + private int CountDirectories() + { + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn); + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + + private int CountFiles() + { + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn); + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + private void CreateTables() { using var conn = GetConnection(); @@ -537,6 +547,13 @@ namespace slskd.Shares conn.ExecuteNonQuery("DROP TABLE IF EXISTS exclusions; CREATE TABLE exclusions (originalFilename TEXT PRIMARY KEY);"); } + private SqliteConnection GetConnection() + { + var conn = new SqliteConnection(Program.ConnectionStrings.Shares); + conn.Open(); + return conn; + } + private void InsertDirectory(string name) { using var conn = GetConnection(); @@ -547,6 +564,29 @@ namespace slskd.Shares }); } + private void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson) " + + "VALUES(@maskedFilename, @originalFilename, @size, @touchedAt, @code, @extension, @attributeJson) " + + "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, size = excluded.size, touchedAt = excluded.touchedAt, code = excluded.code, extension = excluded.extension, attributeJson = excluded.attributeJson;", cmd => + { + cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); + cmd.Parameters.AddWithValue("originalFilename", originalFilename); + cmd.Parameters.AddWithValue("size", file.Size); + cmd.Parameters.AddWithValue("touchedAt", touchedAt.ToLongDateString()); + cmd.Parameters.AddWithValue("code", file.Code); + cmd.Parameters.AddWithValue("extension", file.Extension); + cmd.Parameters.AddWithValue("attributeJson", file.Attributes.ToJson()); + }); + + conn.ExecuteNonQuery("INSERT INTO filenames (maskedFilename) VALUES(@maskedFilename);", cmd => + { + cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); + }); + } + private IEnumerable ListDirectories() { using var conn = GetConnection(); @@ -600,45 +640,20 @@ namespace slskd.Shares } } - private int CountDirectories() - { - using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn); - var reader = cmd.ExecuteReader(); - reader.Read(); - return reader.GetInt32(0); - } - - private int CountFiles() - { - using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn); - var reader = cmd.ExecuteReader(); - reader.Read(); - return reader.GetInt32(0); - } - - private void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file) + private void ResetCache() { - using var conn = GetConnection(); - - conn.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson) " + - "VALUES(@maskedFilename, @originalFilename, @size, @touchedAt, @code, @extension, @attributeJson) " + - "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, size = excluded.size, touchedAt = excluded.touchedAt, code = excluded.code, extension = excluded.extension, attributeJson = excluded.attributeJson;", cmd => - { - cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); - cmd.Parameters.AddWithValue("originalFilename", originalFilename); - cmd.Parameters.AddWithValue("size", file.Size); - cmd.Parameters.AddWithValue("touchedAt", touchedAt.ToLongDateString()); - cmd.Parameters.AddWithValue("code", file.Code); - cmd.Parameters.AddWithValue("extension", file.Extension); - cmd.Parameters.AddWithValue("attributeJson", file.Attributes.ToJson()); - }); + CreateTables(); - conn.ExecuteNonQuery("INSERT INTO filenames (maskedFilename) VALUES(@maskedFilename);", cmd => + try { - cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); - }); + System.IO.File.Delete(Path.Combine(Program.DataDirectory, Filenames.BrowseCache)); + } + catch (FileNotFoundException) + { + // noop + } + + State.SetValue(state => state with { Directories = 0, Files = 0 }); } private bool TableExists(string table) @@ -661,21 +676,5 @@ namespace slskd.Shares return false; } - - private void ResetCache() - { - CreateTables(); - - try - { - System.IO.File.Delete(Path.Combine(Program.DataDirectory, Filenames.BrowseCache)); - } - catch (FileNotFoundException) - { - // noop - } - - State.SetValue(state => state with { Directories = 0, Files = 0 }); - } } } \ No newline at end of file -- cgit v1.2.3 From e012ea79040c3ba2862c178d50d4fab294477c98 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 21:05:01 -0500 Subject: split interface --- src/slskd/Shares/ISharedFileCache.cs | 78 ++++++++++++++++++++++++++++++++++++ src/slskd/Shares/SharedFileCache.cs | 58 +-------------------------- 2 files changed, 80 insertions(+), 56 deletions(-) create mode 100644 src/slskd/Shares/ISharedFileCache.cs (limited to 'src') diff --git a/src/slskd/Shares/ISharedFileCache.cs b/src/slskd/Shares/ISharedFileCache.cs new file mode 100644 index 00000000..7043b030 --- /dev/null +++ b/src/slskd/Shares/ISharedFileCache.cs @@ -0,0 +1,78 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System.Collections.Generic; + using System.Text.RegularExpressions; + using System.Threading.Tasks; + using Soulseek; + + /// + /// Shared file cache. + /// + public interface ISharedFileCache + { + /// + /// Gets the cache state monitor. + /// + IStateMonitor StateMonitor { get; } + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + IEnumerable Browse(); + + /// + /// Scans the configured shares and fills the cache. + /// + /// Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete. + /// The list of shares from which to fill the cache. + /// The list of regular expressions used to exclude files or paths from scanning. + /// The operation context. + Task FillAsync(IEnumerable shares, IEnumerable filters); + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + Directory List(string directory); + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + IEnumerable Search(SearchQuery query); + + /// + /// Attempts to load the cache from disk. + /// + /// A value indicating whether the load was successful. + bool TryLoad(); + } +} diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index ed55fe2a..6490478c 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -31,60 +31,6 @@ namespace slskd.Shares using Serilog; using Soulseek; - /// - /// Shared file cache. - /// - public interface ISharedFileCache - { - /// - /// Gets the cache state monitor. - /// - IStateMonitor StateMonitor { get; } - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - IEnumerable Browse(); - - /// - /// Scans the configured shares and fills the cache. - /// - /// Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete. - /// The list of shares from which to fill the cache. - /// The list of regular expressions used to exclude files or paths from scanning. - /// The operation context. - Task FillAsync(IEnumerable shares, IEnumerable filters); - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - Directory List(string directory); - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename); - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - IEnumerable Search(SearchQuery query); - - /// - /// Attempts to load the cache from disk. - /// - /// A value indicating whether the load was successful. - bool TryLoad(); - } - /// /// Shared file cache. /// @@ -133,7 +79,7 @@ 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 ListDirectories()) + foreach (var directory in ListDirectories().OrderBy(d => d)) { directories.TryAdd(directory, new Directory(directory)); } @@ -169,7 +115,7 @@ namespace slskd.Shares f.Size, f.Extension, f.Attributes); - }))); + }).OrderBy(f => f.Filename))); // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. // entries with no files will remain untouched. -- cgit v1.2.3 From a8ea5d661f2cffb36245f6c166263c6538fb7361 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 21:29:03 -0500 Subject: add Ready state --- src/slskd/Core/State.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index a1da2be8..1b798ad3 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -102,6 +102,7 @@ namespace slskd { public bool ScanPending { get; init; } public bool Scanning { get; init; } + public bool Ready { get; init; } public bool Faulted { get; init; } public double ScanProgress { get; init; } public int Directories { get; init; } -- cgit v1.2.3 From f5374e5b9ed4a6c76278ed0b4e1c462d0396fcbd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 21:30:06 -0500 Subject: set Ready state --- src/slskd/Shares/ShareService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 244d2f9b..316e6b2f 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -52,6 +52,7 @@ namespace slskd.Shares ScanPending = current.Faulted || (!(previous.Filling && !current.Filling) && state.ScanPending), Scanning = current.Filling, Faulted = current.Faulted, + Ready = current.Filled, ScanProgress = current.FillProgress, Directories = current.Directories, Files = current.Files, -- cgit v1.2.3 From e504c397a92f11fbc6ed724b52e1acf041a78850 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 21:30:52 -0500 Subject: refine handling of browse cache --- src/slskd/Application.cs | 51 ++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 07cf5dbd..f3feec23 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -369,13 +369,13 @@ namespace slskd _ = CheckVersionAsync(); } - if (await Shares.TryLoadFromDiskAsync()) + // try to load the share cache from disk. + // if not successful, the file is missing one or more tables, or is not present at all + if (!await Shares.TryLoadFromDiskAsync()) { - Log.Information("Loaded share cache from disk"); - } - else - { - Log.Warning("Failed to load share cache from disk. A share scan is required."); + Log.Warning("Unable to load share cache from disk. A share scan is required."); + + State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); if (OptionsAtStartup.Flags.NoShareScan) { @@ -429,31 +429,18 @@ namespace slskd BrowseResponse response = default; var cacheFilename = Path.Combine(Program.DataDirectory, Filenames.BrowseCache); - var cacheFileInfo = new System.IO.FileInfo(cacheFilename); + var cacheFileInfo = new FileInfo(cacheFilename); if (!cacheFileInfo.Exists) { Log.Warning("Browse response not cached. Rebuilding..."); - - var directories = await Shares.BrowseAsync(); - response = new BrowseResponse(directories); - - Log.Information("Caching browse response..."); - System.IO.File.WriteAllBytes(cacheFilename, response.ToByteArray()); - Log.Information("Browse response cached successfully"); + await CacheBrowseResponse(); } - cacheFileInfo = new System.IO.FileInfo(cacheFilename); - - if (!cacheFileInfo.Exists) - { - throw new IOException("Unable to access recently written browse cache; is the file still open?"); - } - - var stream = new System.IO.FileStream(cacheFilename, FileMode.Open, FileAccess.Read); + var stream = new FileStream(cacheFilename, FileMode.Open, FileAccess.Read); response = new RawBrowseResponse(cacheFileInfo.Length, stream); - Log.Information("Returned cached browse response for {User}", username); + Log.Information("Sent browse response to {User}", username); sw.Stop(); @@ -1017,6 +1004,7 @@ namespace slskd { State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + _ = CacheBrowseResponse(); SharesRefreshStarted = default; @@ -1030,6 +1018,13 @@ namespace slskd } } } + else if (!previous.Ready && current.Ready) + { + // the share transitioned into ready without completing a scan; it was loaded from disk + State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); + Log.Information("Shares loaded from disk successfully. Sharing {Directories} directories and {Files}", current.Directories, current.Files); + _ = CacheBrowseResponse(); + } else { // the scan is neither starting nor finishing; progress update @@ -1044,6 +1039,16 @@ namespace slskd } } + private async Task CacheBrowseResponse() + { + var directories = await Shares.BrowseAsync(); + var response = new BrowseResponse(directories); + + Log.Information("Warming browse response cache..."); + System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, Filenames.BrowseCache), response.ToByteArray()); + Log.Information("Browse response cached successfully"); + } + private void State_OnChange((State Previous, State Current) state) { _ = ApplicationHub.BroadcastStateAsync(state.Current); -- cgit v1.2.3 From 253483c7157cf863b816fde348151a57c1505e38 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 8 Sep 2022 21:37:04 -0500 Subject: clean up --- src/slskd/Shares/SharedFileCache.cs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 6490478c..7f75668b 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -342,7 +342,7 @@ namespace slskd.Shares return null; } - var files = ListFiles(directory); + var files = ListFiles(directory).OrderBy(f => f.Filename); return new Directory(directory, files); } @@ -438,6 +438,8 @@ namespace slskd.Shares { if (TableExists("directories") && TableExists("filenames") && TableExists("files") && TableExists("exclusions")) { + // todo: check columns + State.SetValue(state => state with { Filling = false, @@ -489,8 +491,6 @@ namespace slskd.Shares conn.ExecuteNonQuery("DROP TABLE IF EXISTS 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);"); - - conn.ExecuteNonQuery("DROP TABLE IF EXISTS exclusions; CREATE TABLE exclusions (originalFilename TEXT PRIMARY KEY);"); } private SqliteConnection GetConnection() @@ -612,13 +612,8 @@ namespace slskd.Shares if (reader.Read()) { var fetchedTable = reader.GetString(0); - Console.WriteLine($"Fetched: {fetchedTable}"); return table == fetchedTable; } - else - { - Console.WriteLine("Read() was false"); - } return false; } -- cgit v1.2.3 From c527a1f6f6c2f28a4f2775c5d76d844a843762a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 11:39:51 -0500 Subject: fix a bug preventing swagger from working --- src/slskd/Core/Options.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 259977b6..d6d4b04c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -755,12 +755,12 @@ namespace slskd /// Gets metrics endpoint authentication options. /// [Validate] - public AuthenticationOptions Authentication { get; init; } = new AuthenticationOptions(); + public MetricsAuthenticationOptions Authentication { get; init; } = new MetricsAuthenticationOptions(); /// /// Metrics endpoint authentication options. /// - public class AuthenticationOptions + public class MetricsAuthenticationOptions { /// /// Gets a value indicating whether authentication should be disabled. @@ -1114,12 +1114,12 @@ namespace slskd /// Gets authentication options. /// [Validate] - public AuthenticationOptions Authentication { get; init; } = new AuthenticationOptions(); + public WebAuthenticationOptions Authentication { get; init; } = new WebAuthenticationOptions(); /// /// Authentication options. /// - public class AuthenticationOptions + public class WebAuthenticationOptions { /// /// Gets a value indicating whether authentication should be disabled. -- cgit v1.2.3 From 1955793824df698ce1f4aa3a130d327e20875efd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 12:22:13 -0500 Subject: defer sorting to SQLite, don't use yield --- src/slskd/Shares/SharedFileCache.cs | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 7f75668b..c7c1d30a 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -79,7 +79,7 @@ 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 ListDirectories().OrderBy(d => d)) + foreach (var directory in ListDirectories()) { directories.TryAdd(directory, new Directory(directory)); } @@ -87,7 +87,7 @@ namespace slskd.Shares var files = new List(); using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", conn); + using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); var reader = cmd.ExecuteReader(); while (reader.Read()) @@ -124,7 +124,7 @@ namespace slskd.Shares directories.AddOrUpdate(group.Name, group, (_, _) => group); } - return directories.Values; + return directories.Values.OrderBy(d => d.Name); } /// @@ -342,7 +342,7 @@ namespace slskd.Shares return null; } - var files = ListFiles(directory).OrderBy(f => f.Filename); + var files = ListFiles(directory); return new Directory(directory, files); } @@ -394,7 +394,8 @@ namespace slskd.Shares var sql = $"SELECT files.maskedFilename, files.code, files.size, files.extension, files.attributeJson FROM filenames " + "INNER JOIN files ON filenames.maskedFilename = files.maskedFilename " + - $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}';"; + $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}' " + + "ORDER BY filenames.maskedFilename ASC;"; var results = new List(); SqliteDataReader reader = default; @@ -419,7 +420,7 @@ namespace slskd.Shares results.Add(file); } - return results; + return results.OrderBy(f => f.Filename); } catch (Exception ex) { @@ -535,19 +536,25 @@ namespace slskd.Shares private IEnumerable ListDirectories() { + var results = new List(); + using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT name FROM directories;", conn); + using var cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); var reader = cmd.ExecuteReader(); while (reader.Read()) { - yield return reader.GetString(0); + results.Add(reader.GetString(0)); } + + return results; } private IEnumerable ListFiles(string directory = null) { + var results = new List(); + SqliteCommand cmd = default; using var conn = GetConnection(); @@ -555,11 +562,11 @@ namespace slskd.Shares { if (string.IsNullOrEmpty(directory)) { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files;", conn); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); } else { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match;", conn); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ORDER BY maskedFilename ASC;", conn); cmd.Parameters.AddWithValue("match", directory + '%'); } @@ -577,8 +584,10 @@ namespace slskd.Shares var file = new File(code, filename: Path.GetFileName(filename), size, extension, attributeList); - yield return file; + results.Add(file); } + + return results; } finally { -- cgit v1.2.3 From b0420bd49b64995671b80deeef54cffece0a4d41 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 13:14:45 -0500 Subject: add StorageType --- src/slskd/Core/Types/StorageType.cs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/slskd/Core/Types/StorageType.cs (limited to 'src') diff --git a/src/slskd/Core/Types/StorageType.cs b/src/slskd/Core/Types/StorageType.cs new file mode 100644 index 00000000..63b19899 --- /dev/null +++ b/src/slskd/Core/Types/StorageType.cs @@ -0,0 +1,35 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Storage type. + /// + public enum StorageType + { + /// + /// Stored in memory. + /// + Memory = 0, + + /// + /// Stored on disk. + /// + Disk = 1, + } +} -- cgit v1.2.3 From 5e11cc0fc0703dc161140b28f7e2cd0f65facf9c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 13:17:18 -0500 Subject: consolidate share options, add cache storage option --- config/slskd.example.yml | 12 ++++---- src/slskd/Core/Options.cs | 76 +++++++++++++++++++++++++++++++++++++---------- 2 files changed, 68 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 7038c576..46033bff 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -12,8 +12,14 @@ # directories: # incomplete: ~ # downloads: ~ -# shared: +# shares: +# directories: # - ~ +# filters: +# - \.ini$ +# - Thumbs.db$ +# - \.DS_Store$ +# cache_storage: memory # rooms: # - ~ # global: @@ -48,10 +54,6 @@ # - alice # - bob # filters: -# share: -# - \.ini$ -# - Thumbs.db$ -# - \.DS_Store$ # search: # request: # - ^.{1,2}$ diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index d6d4b04c..327036aa 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -196,6 +196,13 @@ namespace slskd [RequiresRestart] public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions(); + /// + /// Gets share options. + /// + [Validate] + [RequiresRestart] + public SharesOptions Shares { get; init; } = new SharesOptions(); + /// /// Gets global options. /// @@ -324,7 +331,7 @@ namespace slskd /// /// Directory options. /// - public class DirectoriesOptions : IValidatableObject + public class DirectoriesOptions { /// /// Gets the path where incomplete downloads are saved. @@ -345,14 +352,36 @@ namespace slskd [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; + } + /// + /// Share options. + /// + public class SharesOptions : IValidatableObject + { /// /// Gets the list of paths to shared files. /// [Argument('s', "shared")] [EnvironmentVariable("SHARED_DIR")] - [Description("path to shared files")] - public string[] Shared { get; init; } = Array.Empty(); + [Description("paths to shared files")] + public string[] Directories { get; init; } = Array.Empty(); + + /// + /// Gets the list of shared file filters. + /// + [Argument(default, "share-filter")] + [EnvironmentVariable("SHARE_FILTER")] + [Description("regular expressions to filter files from shares")] + public string[] Filters { get; init; } = Array.Empty(); + + /// + /// Gets the type of storage to use for the share cache. + /// + [Argument(default, "share-cache-storage")] + [EnvironmentVariable("SHARE_CACHE_STORAGE")] + [Description("the type of storage to use for the cache")] + public StorageType CacheStorage { get; init; } = StorageType.Memory; /// /// Extended validation. @@ -363,17 +392,27 @@ namespace slskd { var results = new List(); + results.AddRange(ValidateShares()); + results.AddRange(ValidateFilters()); + + return results; + } + + private IEnumerable ValidateShares() + { + var results = new List(); + bool IsBlankPath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])$"); - Shared.Where(share => IsBlankPath(share)).ToList() + Directories.Where(share => IsBlankPath(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} doees not specify a path"))); bool IsRootMount(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])/$"); - Shared.Where(share => IsRootMount(share)).ToList() + Directories.Where(share => IsRootMount(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported."))); // starts with '/', 'X:', or '\\' bool IsAbsolutePath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); - Shared.Where(share => !IsAbsolutePath(share)).ToList() + Directories.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); (string Raw, string Alias, string Path) Digest(string share) @@ -388,7 +427,7 @@ namespace slskd return (share, share.Split(new[] { '/', '\\' }).Last(), share); } - var digestedShared = Shared + var digestedShared = Directories .Select(share => Digest(share.TrimEnd('/', '\\'))) .ToHashSet(); @@ -415,6 +454,21 @@ namespace slskd return results; } + + private IEnumerable ValidateFilters() + { + var results = new List(); + + foreach (var filter in Filters) + { + if (!filter.IsValidRegex()) + { + results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); + } + } + + return results; + } } /// @@ -644,14 +698,6 @@ namespace slskd /// public class FiltersOptions : IValidatableObject { - /// - /// Gets the list of shared file filters. - /// - [Argument(default, "share-filter")] - [EnvironmentVariable("SHARE_FILTER")] - [Description("regular expressions to filter files from shares")] - public string[] Share { get; init; } = Array.Empty(); - /// /// Gets search filter options. /// -- cgit v1.2.3 From dab9af45aa0d06b882c661fc3cddb6af6f61545e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:37:33 -0500 Subject: add cache type --- config/slskd.example.yml | 3 ++- src/slskd/Core/Options.cs | 47 ++++++++++++++++++++--------------------------- 2 files changed, 22 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 46033bff..1f628077 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -19,7 +19,8 @@ # - \.ini$ # - Thumbs.db$ # - \.DS_Store$ -# cache_storage: memory +# cache: +# storage_mode: Memory # rooms: # - ~ # global: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 327036aa..2d561e29 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -200,7 +200,6 @@ namespace slskd /// Gets share options. /// [Validate] - [RequiresRestart] public SharesOptions Shares { get; init; } = new SharesOptions(); /// @@ -376,12 +375,26 @@ namespace slskd public string[] Filters { get; init; } = Array.Empty(); /// - /// Gets the type of storage to use for the share cache. + /// Share caching options. /// - [Argument(default, "share-cache-storage")] - [EnvironmentVariable("SHARE_CACHE_STORAGE")] - [Description("the type of storage to use for the cache")] - public StorageType CacheStorage { get; init; } = StorageType.Memory; + [Validate] + public ShareCacheOptions Cache { get; init; } = new ShareCacheOptions(); + + /// + /// Share caching options. + /// + public class ShareCacheOptions + { + /// + /// Gets the type of storage to use for the share cache. + /// + [Argument(default, "share-cache-storage-mode")] + [EnvironmentVariable("SHARE_CACHE_STORAGE_MODE")] + [Description("the type of storage to use for the cache")] + [Enum(typeof(StorageMode))] + [RequiresRestart] + public string StorageMode { get; init; } = slskd.StorageMode.Memory.ToString().ToLowerInvariant(); + } /// /// Extended validation. @@ -696,7 +709,7 @@ namespace slskd /// /// Filter options. /// - public class FiltersOptions : IValidatableObject + public class FiltersOptions { /// /// Gets search filter options. @@ -704,26 +717,6 @@ namespace slskd [Validate] public SearchOptions Search { get; init; } = new SearchOptions(); - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - foreach (var filter in Share) - { - if (!filter.IsValidRegex()) - { - results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); - } - } - - return results; - } - /// /// Search filter options. /// -- cgit v1.2.3 From 523ece5b03e4eb5ff298da7257239a728ea1aab4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:37:50 -0500 Subject: add ToEnum --- src/slskd/Common/CommonExtensions.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 6f39d17f..9b6a3c6c 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -359,6 +359,17 @@ namespace slskd obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); } + /// + /// Casts the string to . + /// + /// The Enum type to which to cast. + /// The string to cast. + /// The cast enum + public static T ToEnum(this string str) + { + return (T)Enum.Parse(typeof(T), str, ignoreCase: true); + } + /// /// Deserializes this string from json to an object of type . /// -- cgit v1.2.3 From 79649ecdc4e49a01de85d099f449662cb78f23df Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:38:12 -0500 Subject: StorageType -> StorageMode --- src/slskd/Core/Types/StorageMode.cs | 35 +++++++++++++++++++++++++++++++++++ src/slskd/Core/Types/StorageType.cs | 35 ----------------------------------- 2 files changed, 35 insertions(+), 35 deletions(-) create mode 100644 src/slskd/Core/Types/StorageMode.cs delete mode 100644 src/slskd/Core/Types/StorageType.cs (limited to 'src') diff --git a/src/slskd/Core/Types/StorageMode.cs b/src/slskd/Core/Types/StorageMode.cs new file mode 100644 index 00000000..aced3050 --- /dev/null +++ b/src/slskd/Core/Types/StorageMode.cs @@ -0,0 +1,35 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Storage mode. + /// + public enum StorageMode + { + /// + /// Stored in memory. + /// + Memory = 0, + + /// + /// Stored on disk. + /// + Disk = 1, + } +} diff --git a/src/slskd/Core/Types/StorageType.cs b/src/slskd/Core/Types/StorageType.cs deleted file mode 100644 index 63b19899..00000000 --- a/src/slskd/Core/Types/StorageType.cs +++ /dev/null @@ -1,35 +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 -{ - /// - /// Storage type. - /// - public enum StorageType - { - /// - /// Stored in memory. - /// - Memory = 0, - - /// - /// Stored on disk. - /// - Disk = 1, - } -} -- cgit v1.2.3 From bc362491446e4bfa94b7891ac0694d4f9b35df16 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:38:37 -0500 Subject: add share backup, remove Filenames --- src/slskd/Core/ConnectionStrings.cs | 1 + src/slskd/Core/Filenames.cs | 30 ------------------------------ 2 files changed, 1 insertion(+), 30 deletions(-) delete mode 100644 src/slskd/Core/Filenames.cs (limited to 'src') diff --git a/src/slskd/Core/ConnectionStrings.cs b/src/slskd/Core/ConnectionStrings.cs index e5bd4f05..6afab93f 100644 --- a/src/slskd/Core/ConnectionStrings.cs +++ b/src/slskd/Core/ConnectionStrings.cs @@ -24,6 +24,7 @@ namespace slskd { 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/Core/Filenames.cs b/src/slskd/Core/Filenames.cs deleted file mode 100644 index 0fc55fc5..00000000 --- a/src/slskd/Core/Filenames.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - /// - /// Application files. - /// - public static class Filenames - { - public static readonly string TransfersDb = "transfers.db"; - public static readonly string SharesDb = "shares.db"; - public static readonly string SearchDb = "search.db"; - public static readonly string BrowseCache = "browse.cache"; - } -} -- cgit v1.2.3 From cad5239f816bc3f116a6ad8d3dea9e1e3f831a65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:38:57 -0500 Subject: simplify enum handling --- src/slskd/Integrations/FTP/FTPClientFactory.cs | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index 2e41ab03..70cfbc03 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -47,24 +47,10 @@ namespace slskd.Integrations.FTP public FtpClient CreateFtpClient() { var client = new FtpClient(FtpOptions.Address, FtpOptions.Port, FtpOptions.Username, FtpOptions.Password); - client.EncryptionMode = ParseFtpEncryptionMode(FtpOptions.EncryptionMode); + client.EncryptionMode = FtpOptions.EncryptionMode.ToEnum(); client.ValidateAnyCertificate = FtpOptions.IgnoreCertificateErrors; return client; } - - private FtpEncryptionMode ParseFtpEncryptionMode(string encryptionMode) - { - try - { - return (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), encryptionMode, ignoreCase: true); - } - catch (Exception ex) - { - // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this - // throws there's a bug somewhere. - throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); - } - } } } \ No newline at end of file -- cgit v1.2.3 From 7c4922e890bf0267ceb55ff568d03b0485edbd4d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:39:44 -0500 Subject: backup and restore share cache from disk --- src/slskd/Shares/ShareService.cs | 8 +-- src/slskd/Shares/SharedFileCache.cs | 113 +++++++++++++++++++++++++----------- 2 files changed, 84 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 316e6b2f..dd808360 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -41,7 +41,7 @@ namespace slskd.Shares IOptionsMonitor optionsMonitor, ISharedFileCache sharedFileCache = null) { - Cache = sharedFileCache ?? new SharedFileCache(); + Cache = sharedFileCache ?? new SharedFileCache(storageMode: optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum()); Cache.StateMonitor.OnChange(cacheState => { var (previous, current) = cacheState; @@ -180,21 +180,21 @@ namespace slskd.Shares try { - var optionsHash = Compute.Sha1Hash(string.Join(';', options.Directories.Shared)); + var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories)); if (optionsHash == LastOptionsHash) { return; } - var shares = options.Directories.Shared + var shares = options.Shares.Directories .Select(share => share.TrimEnd('/', '\\')) .ToHashSet() // remove duplicates .Select(share => new Share(share)) // convert to Shares .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent .ToList(); - var regexes = options.Filters.Share + var regexes = options.Shares.Filters .Select(filter => new Regex(filter, RegexOptions.Compiled)) .ToList(); diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index c7c1d30a..2c14024e 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -22,6 +22,7 @@ namespace slskd.Shares using System; using System.Collections.Concurrent; using System.Collections.Generic; + using System.Data; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; @@ -39,9 +40,11 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// + /// /// - public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null) + public SharedFileCache(StorageMode storageMode, ISoulseekFileFactory soulseekFileFactory = null) { + StorageMode = storageMode; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); } @@ -50,6 +53,7 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor => State; + private StorageMode StorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } @@ -144,19 +148,24 @@ namespace slskd.Shares try { + // drop and recreate the tables to clear them + // note: leave the backup in place. this will leave the app in a better position if the app stops during the scan. + CreateTables(); + State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0, + Directories = 0, + Files = 0, + ExcludedDirectories = 0, }); Log.Debug("Starting shared file scan"); await Task.Yield(); - ResetCache(); - var sw = new Stopwatch(); var swSnapshot = 0L; sw.Start(); @@ -301,6 +310,10 @@ namespace slskd.Shares Log.Debug("Inserted {Files} records in {Elapsed}ms", cached, sw.ElapsedMilliseconds - swSnapshot); + Log.Debug("Backing up shared file cache database..."); + Backup(); + Log.Debug("Shared file cache database backup complete"); + State.SetValue(state => state with { Filling = false, @@ -437,24 +450,48 @@ namespace slskd.Shares { try { - if (TableExists("directories") && TableExists("filenames") && TableExists("files") && TableExists("exclusions")) + // see if we need to 'restore' the database from disk + if (StorageMode == StorageMode.Memory || (StorageMode == StorageMode.Disk && !DatabaseExists(Program.ConnectionStrings.Shares))) { - // todo: check columns + Log.Debug($"Share cache {(StorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup..."); - State.SetValue(state => state with + // the backup is missing; we can't do anything but recreate it from scratch + if (!DatabaseExists(Program.ConnectionStrings.SharesBackup)) { - Filling = false, - Faulted = false, - Filled = true, - FillProgress = 1, - Directories = CountDirectories(), - Files = CountFiles(), - }); + Log.Debug("Share cache backup is missing; unable to restore"); + return false; + } - return true; + Log.Debug("Share cache backup located. Attempting to restore..."); + + using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup); + using var conn = GetConnection(); + backupConn.BackupDatabase(conn); + + Log.Debug("Share cache successfully restored from backup"); } - return false; + Log.Debug("Validating share cache database"); + + if (!TableExists("directories") || !TableExists("filenames") || !TableExists("files")) + { + Log.Warning("One or more tables are missing from the share cache database"); + return false; + } + + // todo: check columns + + State.SetValue(state => state with + { + Filling = false, + Faulted = false, + Filled = true, + FillProgress = 1, + Directories = CountDirectories(), + Files = CountFiles(), + }); + + return true; } catch (Exception ex) { @@ -463,6 +500,32 @@ namespace slskd.Shares } } + private bool DatabaseExists(string connectionString) + { + try + { + using var conn = GetConnection(connectionString); + + if (conn.State == ConnectionState.Open) + { + return true; + } + + return false; + } + catch + { + return false; + } + } + + private void Backup() + { + using var sourceConn = GetConnection(); + using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup); + sourceConn.BackupDatabase(backupConn); + } + private int CountDirectories() { using var conn = GetConnection(); @@ -494,9 +557,9 @@ namespace slskd.Shares "extension TEXT, attributeJson TEXT NOT NULL);"); } - private SqliteConnection GetConnection() + private SqliteConnection GetConnection(string connectionString = null) { - var conn = new SqliteConnection(Program.ConnectionStrings.Shares); + var conn = new SqliteConnection(connectionString ?? Program.ConnectionStrings.Shares); conn.Open(); return conn; } @@ -595,22 +658,6 @@ namespace slskd.Shares } } - private void ResetCache() - { - CreateTables(); - - try - { - System.IO.File.Delete(Path.Combine(Program.DataDirectory, Filenames.BrowseCache)); - } - catch (FileNotFoundException) - { - // noop - } - - State.SetValue(state => state with { Directories = 0, Files = 0 }); - } - private bool TableExists(string table) { using var conn = GetConnection(); -- cgit v1.2.3 From 8f12409567360bb08a9ce9a5d104786c27705a9d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:40:03 -0500 Subject: simplify enum handling --- src/slskd/Transfers/Uploads/UploadQueue.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 54b9a6c3..2c7e3eac 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -402,7 +402,7 @@ namespace slskd.Transfers Priority = options.Groups.Default.Upload.Priority, Slots = Math.Min(options.Groups.Default.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(Application.DefaultGroup), - Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Default.Upload.Strategy, true), + Strategy = options.Groups.Default.Upload.Strategy.ToEnum(), }, new UploadGroup() { @@ -410,7 +410,7 @@ namespace slskd.Transfers Priority = options.Groups.Leechers.Upload.Priority, Slots = Math.Min(options.Groups.Leechers.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(Application.LeecherGroup), - Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Leechers.Upload.Strategy, true), + Strategy = options.Groups.Leechers.Upload.Strategy.ToEnum(), }, }; @@ -421,7 +421,7 @@ namespace slskd.Transfers Priority = kvp.Value.Upload.Priority, Slots = Math.Min(kvp.Value.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(kvp.Key), - Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true), + Strategy = kvp.Value.Upload.Strategy.ToEnum(), })); Groups = groups.ToDictionary(g => g.Name); -- cgit v1.2.3 From e624d3bdc8a4eff1f3b97294ced81647b80983e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:40:30 -0500 Subject: hard code filenames, delete browse cache on scan start --- src/slskd/Application.cs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index f3feec23..288ba07b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -428,7 +428,7 @@ namespace slskd BrowseResponse response = default; - var cacheFilename = Path.Combine(Program.DataDirectory, Filenames.BrowseCache); + var cacheFilename = Path.Combine(Program.DataDirectory, "browse.cache"); var cacheFileInfo = new FileInfo(cacheFilename); if (!cacheFileInfo.Exists) @@ -780,15 +780,15 @@ namespace slskd pendingReconnect |= requiresReconnect; } - if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() - || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) + if (PreviousOptions.Shares.Directories.Except(newOptions.Shares.Directories).Any() + || newOptions.Shares.Directories.Except(PreviousOptions.Shares.Directories).Any()) { State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); Log.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect."); } - if (PreviousOptions.Filters.Share.Except(newOptions.Filters.Share).Any() - || newOptions.Filters.Share.Except(PreviousOptions.Filters.Share).Any()) + if (PreviousOptions.Shares.Filters.Except(newOptions.Shares.Filters).Any() + || newOptions.Shares.Filters.Except(PreviousOptions.Shares.Filters).Any()) { State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); Log.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect."); @@ -989,7 +989,17 @@ namespace slskd SharesRefreshStarted = DateTime.UtcNow; State.SetValue(s => s with { Shares = current }); - Log.Information("Scanning shares"); + Log.Information("Share scan started"); + + try + { + System.IO.File.Delete(Path.Combine(Program.DataDirectory, "browse.cache")); + Log.Information("Cleared browse response cache"); + } + catch + { + // noop + } } else if (previous.Scanning && !current.Scanning) { @@ -1022,7 +1032,7 @@ namespace slskd { // the share transitioned into ready without completing a scan; it was loaded from disk State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); - Log.Information("Shares loaded from disk successfully. Sharing {Directories} directories and {Files}", current.Directories, current.Files); + Log.Information("Shares loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files); _ = CacheBrowseResponse(); } else @@ -1045,7 +1055,7 @@ namespace slskd var response = new BrowseResponse(directories); Log.Information("Warming browse response cache..."); - System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, Filenames.BrowseCache), response.ToByteArray()); + System.IO.File.WriteAllBytes(Path.Combine(Program.DataDirectory, "browse.cache"), response.ToByteArray()); Log.Information("Browse response cached successfully"); } -- cgit v1.2.3 From 1cc28437711fdca0643f01191f84325e3b2359cb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Sep 2022 17:41:06 -0500 Subject: hard code filenames, make SQLite init more prominent --- src/slskd/Program.cs | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f4e59456..5a5d9ce9 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -252,17 +252,31 @@ namespace slskd return; } + InitSQLiteOrFailFast(); + // the application isn't being run in command mode. derive the application directory value // and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; - DataDirectory = Path.Combine(AppDirectory, "data"); + // configure connection strings and configure SQLite + string shareDbDataSource = default; + + if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == StorageMode.Disk) + { + shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); + } + else + { + shareDbDataSource = "file:shares?mode=memory"; + } + ConnectionStrings = new() { - Search = $"Data Source={Path.Combine(DataDirectory, Filenames.SearchDb)};Cache=shared;Pooling=True;", - Transfers = $"Data Source={Path.Combine(DataDirectory, Filenames.TransfersDb)};Cache=shared;Pooling=True;", - Shares = $"Data Source={Path.Combine(DataDirectory, Filenames.SharesDb)};Cache=shared", + 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")};", }; DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml"); @@ -465,8 +479,6 @@ namespace slskd services.AddSingleton(); - ConfigureSQLite(); - services.AddDbContext(ConnectionStrings.Search); services.AddDbContext(ConnectionStrings.Transfers); @@ -492,7 +504,7 @@ namespace slskd return services; } - private static void ConfigureSQLite() + private static void InitSQLiteOrFailFast() { // initialize // avoids: System.Exception: You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init(). -- cgit v1.2.3 From 17a3f6c29799b2ee8fcb38a45a4b178e59ffa83a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Sep 2022 12:01:08 -0500 Subject: fully validate schemas --- src/slskd/Shares/SharedFileCache.cs | 81 +++++++++++++++++++++---------------- 1 file changed, 47 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 2c14024e..e865ff8d 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -450,13 +450,13 @@ namespace slskd.Shares { try { - // see if we need to 'restore' the database from disk - if (StorageMode == StorageMode.Memory || (StorageMode == StorageMode.Disk && !DatabaseExists(Program.ConnectionStrings.Shares))) + // see if we need to 'restore' the database from disk, and do so + if (StorageMode == StorageMode.Memory || (StorageMode == StorageMode.Disk && !ValidateTables(Program.ConnectionStrings.Shares))) { Log.Debug($"Share cache {(StorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup..."); // the backup is missing; we can't do anything but recreate it from scratch - if (!DatabaseExists(Program.ConnectionStrings.SharesBackup)) + if (!ValidateTables(Program.ConnectionStrings.SharesBackup)) { Log.Debug("Share cache backup is missing; unable to restore"); return false; @@ -471,16 +471,11 @@ namespace slskd.Shares Log.Debug("Share cache successfully restored from backup"); } - Log.Debug("Validating share cache database"); - - if (!TableExists("directories") || !TableExists("filenames") || !TableExists("files")) - { - Log.Warning("One or more tables are missing from the share cache database"); - return false; - } - - // todo: check columns - + // one of several thigns happened above before we got here: + // the storage mode is memory, and we loaded the in-memory db from a valid backup + // the storage mode is disk, and the file is there and valid + // the storage mode is disk but either missing or invalid, and we restored from a valid backup + // at this point there is a valid (existing, schema matching expected schema) database at the primary connection string State.SetValue(state => state with { Filling = false, @@ -500,21 +495,55 @@ namespace slskd.Shares } } - private bool DatabaseExists(string connectionString) + private bool ValidateTables(string connectionString) { + var schema = new Dictionary() + { + { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY)" }, + { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, + { "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)" }, + }; + try { + Log.Debug("Validating shares database with connection string {String}", connectionString); + using var conn = GetConnection(connectionString); + using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table' AND name IN ('directories', 'filenames', 'files');", 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 (conn.State == ConnectionState.Open) + if (rows != schema.Count) { - return true; + throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}"); } - return false; + return true; } - catch + catch (Exception ex) { + Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); return false; } } @@ -657,21 +686,5 @@ namespace slskd.Shares cmd?.Dispose(); } } - - private bool TableExists(string table) - { - using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT name from sqlite_master WHERE type = 'table' AND name = @table;", conn); - cmd.Parameters.AddWithValue("table", table); - var reader = cmd.ExecuteReader(); - - if (reader.Read()) - { - var fetchedTable = reader.GetString(0); - return table == fetchedTable; - } - - return false; - } } } \ No newline at end of file -- cgit v1.2.3 From 2a0db7e44a0b25d2a505ae8472de214c6c68b5d2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Sep 2022 12:02:17 -0500 Subject: move connection string setup --- src/slskd/Program.cs | 49 +++++++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 5a5d9ce9..fe2bb626 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -252,33 +252,11 @@ namespace slskd return; } - InitSQLiteOrFailFast(); - // the application isn't being run in command mode. derive the application directory value // and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; DataDirectory = Path.Combine(AppDirectory, "data"); - // configure connection strings and configure SQLite - string shareDbDataSource = default; - - if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == StorageMode.Disk) - { - shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); - } - else - { - 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")};", - }; - DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml"); DefaultDownloadsDirectory = Path.Combine(AppDirectory, "downloads"); DefaultIncompleteDirectory = Path.Combine(AppDirectory, "incomplete"); @@ -355,11 +333,38 @@ namespace slskd Log.Information("Process ID: {ProcessId}", ProcessId); Log.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); + // SQLite must have specific capabilities to function properly. this shouldn't be a concern for shrinkwrapped + // binaries or in Docker, but if someone builds from source weird things can happen. + InitSQLiteOrFailFast(); + Log.Information("Using application directory {AppDirectory}", AppDirectory); Log.Information("Using configuration file {ConfigurationFile}", ConfigurationFile); + Log.Information("Storing application data in {DataDirectory}", DataDirectory); RecreateConfigurationFileIfMissing(ConfigurationFile); + // configure connection strings and configure SQLite + string shareDbDataSource = default; + + if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == StorageMode.Disk) + { + Log.Information("Using on-disk shared file database"); + shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); + } + else + { + Log.Information("Using in-memory shared file database"); + 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); -- cgit v1.2.3 From a596dfe252ef53e41b91ec6773aec93307c41f1e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Sep 2022 18:09:58 -0500 Subject: tweak logging for consistency --- src/slskd/Application.cs | 2 +- src/slskd/Program.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 288ba07b..cab2b649 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1032,7 +1032,7 @@ namespace slskd { // the share transitioned into ready without completing a scan; it was loaded from disk State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); - Log.Information("Shares loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files); + Log.Information("Share cache loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files); _ = CacheBrowseResponse(); } else diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index fe2bb626..e828f242 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -348,12 +348,12 @@ namespace slskd if (OptionsAtStartup.Shares.Cache.StorageMode.ToEnum() == StorageMode.Disk) { - Log.Information("Using on-disk shared file database"); + Log.Information("Using on-disk shared file cache"); shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); } else { - Log.Information("Using in-memory shared file database"); + Log.Information("Using in-memory shared file cache"); shareDbDataSource = "file:shares?mode=memory"; } -- cgit v1.2.3 From d059907653cbbbe2958b320c689003c815acb219 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Sep 2022 21:08:15 -0500 Subject: don't double sort search results --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index e865ff8d..a9400114 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -433,7 +433,7 @@ namespace slskd.Shares results.Add(file); } - return results.OrderBy(f => f.Filename); + return results; } catch (Exception ex) { -- cgit v1.2.3 From bc6278db4a6c8e402ba1c7685d4983b3808ef276 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 13 Sep 2022 09:36:52 -0500 Subject: remove warnings about backslashes in file or directory names --- src/slskd/Shares/SharedFileCache.cs | 12 ------------ 1 file changed, 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index e865ff8d..814e7447 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -231,12 +231,6 @@ namespace slskd.Shares { Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count); - if (Path.DirectorySeparatorChar == '/' && directory.Contains('\\')) - { - Log.Warning("Directory name {Directory} contains one or more backslashes, which are not currently supported. This directory will not be shared.", directory); - continue; - } - var addedFiles = 0; var filteredFiles = 0; @@ -273,12 +267,6 @@ namespace slskd.Shares continue; } - if (Path.DirectorySeparatorChar == '/' && file.Filename.Contains('\\')) - { - Log.Warning("Filename {Filename} contains one or more backslashes, which are not currently supported. This file will not be shared.", file.Filename); - continue; - } - InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file); } } -- cgit v1.2.3 From 9b505173b4c97330dd82c767509a27d945b42d4f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:09:45 -0500 Subject: add an option to set the number of scan workers --- config/slskd.example.yml | 1 + docs/config.md | 7 +++++++ src/slskd/Core/Options.cs | 10 ++++++++++ 3 files changed, 18 insertions(+) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 473d387e..f8658d1c 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -21,6 +21,7 @@ # - \.DS_Store$ # cache: # storage_mode: memory +# workers: 16 # rooms: # - ~ # global: diff --git a/docs/config.md b/docs/config.md index 0580baf5..19692fe3 100644 --- a/docs/config.md +++ b/docs/config.md @@ -166,9 +166,16 @@ Storing the cache on disk uses quite a bit less memory and allows the applicatio The cache is stored in memory by default. If you find that the application uses too much memory or crashes with an `Out of Memory` exception, change this option to store the cache on disk. +Scanning shares is an I/O intensive operation; all of the files and directories in each share have to be listed, and each file has to be read to gather metadata like length, bitrate, and sample rate. To speed things up, multiple 'workers' +are used to allow metadata to be read from several files concurrently. The scan generally gets faster as additional workers are added, but each worker also adds additional I/O pressure and increases CPU and memory usage. At some number of workers +performance will start to get worse as more are added. The optimal number of workers will vary from system to system, so if scan performance is important to you it will be a good idea to experiment to see what the optimal number is for your system. + +The default number of workers is 16. + | Command Line | Environment Variable | Description | | ---------------------------- | -------------------------- | ------------------------------------------------------- | | `--share-cache-storage-mode` | `SHARE_CACHE_STORAGE_MODE` | The type of storage to use for the cache (Memory, Disk) | +| `--share-cache-workers` | `SHARE_CACHE_WORKERS` | The number of workers to use while scanning shares | #### **YAML** ```yaml diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 2d561e29..070476d1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -394,6 +394,16 @@ namespace slskd [Enum(typeof(StorageMode))] [RequiresRestart] public string StorageMode { get; init; } = slskd.StorageMode.Memory.ToString().ToLowerInvariant(); + + /// + /// Gets the number of workers to use while scanning shares. + /// + [Argument(default, "share-cache-workers")] + [EnvironmentVariable("SHARE_CACHE_WORKERS")] + [Description("the number of workers to use while scanning shares")] + [Range(1, 128)] + [RequiresRestart] + public int Workers { get; init; } = 16; } /// -- cgit v1.2.3 From caeaa1ed4f906ad9bd791611d184d93ba2e0e573 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:15:26 -0500 Subject: add SharedFileCacheWorker --- src/slskd/Shares/ISharedFileCacheWorker.cs | 42 +++++++++++++ src/slskd/Shares/SharedFileCacheWorker.cs | 96 ++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 src/slskd/Shares/ISharedFileCacheWorker.cs create mode 100644 src/slskd/Shares/SharedFileCacheWorker.cs (limited to 'src') diff --git a/src/slskd/Shares/ISharedFileCacheWorker.cs b/src/slskd/Shares/ISharedFileCacheWorker.cs new file mode 100644 index 00000000..b6b85c5d --- /dev/null +++ b/src/slskd/Shares/ISharedFileCacheWorker.cs @@ -0,0 +1,42 @@ +// +// 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.Threading.Tasks; + + /// + /// Shared file cache worker. + /// + public interface ISharedFileCacheWorker + { + /// + /// Gets the that completes when the worker has completed all of its work. + /// + Task Completed { get; } + + /// + /// Gets the Id of the worker. + /// + int Id { get; } + + /// + /// Starts the worker. + /// + void Start(); + } +} diff --git a/src/slskd/Shares/SharedFileCacheWorker.cs b/src/slskd/Shares/SharedFileCacheWorker.cs new file mode 100644 index 00000000..6ac5452b --- /dev/null +++ b/src/slskd/Shares/SharedFileCacheWorker.cs @@ -0,0 +1,96 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System; + using System.Threading; + using System.Threading.Channels; + using System.Threading.Tasks; + using Serilog; + + /// + /// Shared file cache worker. + /// + public class SharedFileCacheWorker : ISharedFileCacheWorker + { + /// + /// Initializes a new instance of the class. + /// + /// The worker's unique Id. + /// The channel from which the worker will receive directories to scan. + /// A to monitor for cancellation requests. + /// An to be performed on each item read from the channel. + public SharedFileCacheWorker( + int id, + Channel directoryChannel, + CancellationToken cancellationToken, + Action handler) + { + Id = id; + DirectoryChannel = directoryChannel; + CancellationToken = cancellationToken; + Handler = handler; + } + + /// + /// Gets the that completes when the worker has completed all of its work. + /// + public Task Completed => TaskCompletionSource.Task; + + /// + /// Gets the Id of the worker. + /// + public int Id { get; } + + private Channel DirectoryChannel { get; } + private Action Handler { get; } + private TaskCompletionSource TaskCompletionSource { get; } = new TaskCompletionSource(); + private CancellationToken CancellationToken { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Starts the worker. + /// + public void Start() + { + _ = Read(); + Log.Debug("Shared file cache worker {Id} started", Id); + } + + private async Task Read() + { + try + { + while (!CancellationToken.IsCancellationRequested && !DirectoryChannel.Reader.Completion.IsCompleted) + { + var directory = await DirectoryChannel.Reader.ReadAsync(CancellationToken); + Handler(directory); + } + } + catch (ChannelClosedException) + { + // noop. the channel might close between the time we check and when we go to read; this just means there is no more data. + } + finally + { + Log.Debug($"Shared file cache worker {Id}'s work is complete.", Id); + TaskCompletionSource.SetResult(); + } + } + } +} -- cgit v1.2.3 From bd2d0f0e044376684ddd3176bca1b9101cbd793e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:16:33 -0500 Subject: provide WorkerCount to SharedFileCache --- src/slskd/Shares/ShareService.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index dd808360..96ac4c1c 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -41,7 +41,10 @@ namespace slskd.Shares IOptionsMonitor optionsMonitor, ISharedFileCache sharedFileCache = null) { - Cache = sharedFileCache ?? new SharedFileCache(storageMode: optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum()); + Cache = sharedFileCache ?? new SharedFileCache( + storageMode: optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum(), + workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers); + Cache.StateMonitor.OnChange(cacheState => { var (previous, current) = cacheState; -- cgit v1.2.3 From 6b4753de8ac69deded25ed671497adf2adeba943 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:16:49 -0500 Subject: pass a CancellationToken to FillAsync --- src/slskd/Shares/ISharedFileCache.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/ISharedFileCache.cs b/src/slskd/Shares/ISharedFileCache.cs index 7043b030..52c7783c 100644 --- a/src/slskd/Shares/ISharedFileCache.cs +++ b/src/slskd/Shares/ISharedFileCache.cs @@ -19,6 +19,7 @@ namespace slskd.Shares { using System.Collections.Generic; using System.Text.RegularExpressions; + using System.Threading; using System.Threading.Tasks; using Soulseek; @@ -44,8 +45,9 @@ namespace slskd.Shares /// Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete. /// The list of shares from which to fill the cache. /// The list of regular expressions used to exclude files or paths from scanning. + /// The optional cancellation token to monitor. /// The operation context. - Task FillAsync(IEnumerable shares, IEnumerable filters); + Task FillAsync(IEnumerable shares, IEnumerable filters, CancellationToken cancellationToken = default); /// /// Returns the contents of the specified . -- cgit v1.2.3 From f5ce131f50e74e9c7e5c124de52b48dadbda0b54 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:17:29 -0500 Subject: use a Channel to fan out directory scanning --- src/slskd/Shares/SharedFileCache.cs | 146 +++++++++++++++++++++++------------- 1 file changed, 93 insertions(+), 53 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index fc9052bb..fbd47a5d 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -27,6 +27,7 @@ namespace slskd.Shares using System.Linq; using System.Text.RegularExpressions; using System.Threading; + using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using Serilog; @@ -42,9 +43,10 @@ namespace slskd.Shares /// /// /// - public SharedFileCache(StorageMode storageMode, ISoulseekFileFactory soulseekFileFactory = null) + public SharedFileCache(StorageMode storageMode, int workerCount, ISoulseekFileFactory soulseekFileFactory = null) { StorageMode = storageMode; + WorkerCount = workerCount; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); } @@ -54,11 +56,13 @@ namespace slskd.Shares public IStateMonitor StateMonitor => State; private StorageMode StorageMode { get; } + private int WorkerCount { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + private Channel DirectoryChannel { get; set; } /// /// Returns the contents of the cache. @@ -137,7 +141,7 @@ namespace slskd.Shares /// The list of shares from which to fill the cache. /// The list of regular expressions used to exclude files or paths from scanning. /// The operation context. - public async Task FillAsync(IEnumerable shares, IEnumerable filters) + public async Task FillAsync(IEnumerable shares, IEnumerable filters, CancellationToken cancellationToken = default) { // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) @@ -227,72 +231,108 @@ namespace slskd.Shares var cached = 0; var filtered = 0; - foreach (var directory in unmaskedDirectories) + // set up a channel to fan out for directory scanning + DirectoryChannel = Channel.CreateBounded(new BoundedChannelOptions(1000) { - Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count); - - var addedFiles = 0; - var filteredFiles = 0; - - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + AllowSynchronousContinuations = false, + FullMode = BoundedChannelFullMode.Wait, + SingleReader = false, + SingleWriter = true, + }); - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); - InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + // create workers to perform the fan out + var workers = new List(); - // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized - // filename and with a value of a Soulseek.File object - try - { - // enumerate files in this directory only (no subdirectories) exclude hidden and system files and anything - // that can't be accessed due to security restrictions - var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions() + foreach (var id in Enumerable.Range(0, WorkerCount)) + { + workers.Add(new SharedFileCacheWorker( + id: id, + directoryChannel: DirectoryChannel, + cancellationToken: cancellationToken, + handler: (directory) => { - AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, - IgnoreInaccessible = true, - RecurseSubdirectories = false, - }); + Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count); - addedFiles = newFiles.Count(); + var addedFiles = 0; + var filteredFiles = 0; - // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully - // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var originalFilename in newFiles) - { - var info = new FileInfo(originalFilename); - var file = SoulseekFileFactory.Create(originalFilename, maskedFilename: originalFilename.ReplaceFirst(share.LocalPath, share.RemotePath)); + var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - if (filters.Any(filter => filter.IsMatch(originalFilename))) + maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + + // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized + // filename and with a value of a Soulseek.File object + try + { + // enumerate files in this directory only (no subdirectories) exclude hidden and system files and anything + // that can't be accessed due to security restrictions + var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions() + { + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, + IgnoreInaccessible = true, + RecurseSubdirectories = false, + }); + + addedFiles = newFiles.Count(); + + // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully + // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. + foreach (var originalFilename in newFiles) + { + var info = new FileInfo(originalFilename); + var file = SoulseekFileFactory.Create(originalFilename, maskedFilename: originalFilename.ReplaceFirst(share.LocalPath, share.RemotePath)); + + if (filters.Any(filter => filter.IsMatch(originalFilename))) + { + filteredFiles++; + continue; + } + + InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file); + } + } + catch (Exception ex) { - filteredFiles++; - continue; + Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); + Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); } - InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file); - } - } - catch (Exception ex) - { - Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); - Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); - } + current++; + filtered += filteredFiles; + cached += addedFiles; - current++; - filtered += filteredFiles; - cached += addedFiles; + Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles); - Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles); + try + { + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to set cache state following scan of {Directory}: {Message}", directory, ex.Message); + throw; + } + })); + } - try - { - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to set cache state following scan of {Directory}: {Message}", directory, ex.Message); - throw; - } + Log.Debug("Starting workers..."); + workers.ForEach(w => w.Start()); + Log.Debug("All workers started"); + + Log.Debug("Filling DirectoryChannel..."); + foreach (var directory in unmaskedDirectories) + { + await DirectoryChannel.Writer.WriteAsync(directory); } + DirectoryChannel.Writer.Complete(); + Log.Debug("DirectoryChannel filled"); + + Log.Debug("Waiting for workers to finish working..."); + await Task.WhenAll(workers.Select(w => w.Completed)); + Log.Debug("All workers finished"); + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; -- cgit v1.2.3 From 3279e498bc9da1231e26dd636465a8c2983baa73 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:26:07 -0500 Subject: minor optimization --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index fbd47a5d..1c2b61aa 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -274,7 +274,7 @@ namespace slskd.Shares RecurseSubdirectories = false, }); - addedFiles = newFiles.Count(); + addedFiles = newFiles.Length; // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. -- cgit v1.2.3 From 2700743d8b7b049a8c5fe20f398354e28ce1a94b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Sep 2022 17:32:31 -0500 Subject: fix log message --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index fc9052bb..59abc789 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -293,7 +293,7 @@ namespace slskd.Shares } } - Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; Log.Debug("Inserted {Files} records in {Elapsed}ms", cached, sw.ElapsedMilliseconds - swSnapshot); -- cgit v1.2.3 From 938e610419bbadd0e194c4b789409453399e85ba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Sep 2022 13:03:33 -0500 Subject: refactor SharedFileCacheWorker into ChannelReader --- src/slskd/Common/ChannelReader.cs | 139 +++++++++++++++++++++++++++++ src/slskd/Shares/ISharedFileCacheWorker.cs | 42 --------- src/slskd/Shares/SharedFileCache.cs | 8 +- src/slskd/Shares/SharedFileCacheWorker.cs | 96 -------------------- 4 files changed, 143 insertions(+), 142 deletions(-) create mode 100644 src/slskd/Common/ChannelReader.cs delete mode 100644 src/slskd/Shares/ISharedFileCacheWorker.cs delete mode 100644 src/slskd/Shares/SharedFileCacheWorker.cs (limited to 'src') diff --git a/src/slskd/Common/ChannelReader.cs b/src/slskd/Common/ChannelReader.cs new file mode 100644 index 00000000..f358fb07 --- /dev/null +++ b/src/slskd/Common/ChannelReader.cs @@ -0,0 +1,139 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System; + using System.Threading; + using System.Threading.Channels; + using System.Threading.Tasks; + + /// + /// Reads and handles items from a channel. + /// + public interface IChannelReader + { + /// + /// Gets the that completes when the reader has read all available items from the channel. + /// + Task Completed { get; } + + /// + /// Gets a value indicating whether the reader has started reading. + /// + bool Started { get; } + + /// + /// Starts the reader. + /// + void Start(); + } + + /// + /// Shared file cache worker. + /// + /// The type of the underlying channel. + public class ChannelReader : IChannelReader + { + /// + /// Initializes a new instance of the class. + /// + /// The channel from which the reader will read. + /// An to be invoked for each item read from the channel. + /// An optional to be invoked if the reader encounters an . + /// An optional value indicating whether to automatically start the reader. + /// An optional to monitor for cancellation. + public ChannelReader( + Channel channel, + Action handler, + Action exceptionHandler = null, + bool automaticallyStart = true, + CancellationToken cancellationToken = default) + { + Channel = channel; + Handler = handler; + ExceptionHandler = exceptionHandler; + + CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + CancellationToken = CancellationTokenSource.Token; + + if (automaticallyStart) + { + Start(); + } + } + + /// + /// Gets the that completes when the worker has completed all of its work. + /// + public Task Completed => TaskCompletionSource.Task; + + /// + /// Gets a value indicating whether the reader has started reading. + /// + public bool Started { get; private set; } + + private Channel Channel { get; } + private Action Handler { get; } + private Action ExceptionHandler { get; } + private TaskCompletionSource TaskCompletionSource { get; } = new TaskCompletionSource(); + private CancellationTokenSource CancellationTokenSource { get; } + private CancellationToken CancellationToken { get; } + private object SyncRoot { get; } = new object(); + + /// + /// Starts the reader. + /// + public void Start() + { + lock (SyncRoot) + { + if (!Started) + { + _ = Read(); + Started = true; + } + } + } + + private async Task Read() + { + try + { + while (Started && !CancellationTokenSource.Token.IsCancellationRequested && !Channel.Reader.Completion.IsCompleted) + { + var item = await Channel.Reader.ReadAsync(CancellationToken); + Handler(item); + } + } + catch (ChannelClosedException) + { + // noop. the channel might close between the time we check and when we go to read; this just means there is no more data. + } + catch (Exception ex) + { + ExceptionHandler?.Invoke(ex); + TaskCompletionSource.SetException(ex); + throw; + } + finally + { + TaskCompletionSource.SetResult(); + } + } + } +} diff --git a/src/slskd/Shares/ISharedFileCacheWorker.cs b/src/slskd/Shares/ISharedFileCacheWorker.cs deleted file mode 100644 index b6b85c5d..00000000 --- a/src/slskd/Shares/ISharedFileCacheWorker.cs +++ /dev/null @@ -1,42 +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.Threading.Tasks; - - /// - /// Shared file cache worker. - /// - public interface ISharedFileCacheWorker - { - /// - /// Gets the that completes when the worker has completed all of its work. - /// - Task Completed { get; } - - /// - /// Gets the Id of the worker. - /// - int Id { get; } - - /// - /// Starts the worker. - /// - void Start(); - } -} diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 1c2b61aa..6a0cf87c 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -42,6 +42,7 @@ namespace slskd.Shares /// Initializes a new instance of the class. /// /// + /// /// public SharedFileCache(StorageMode storageMode, int workerCount, ISoulseekFileFactory soulseekFileFactory = null) { @@ -241,13 +242,12 @@ namespace slskd.Shares }); // create workers to perform the fan out - var workers = new List(); + var workers = new List>(); foreach (var id in Enumerable.Range(0, WorkerCount)) { - workers.Add(new SharedFileCacheWorker( - id: id, - directoryChannel: DirectoryChannel, + workers.Add(new ChannelReader( + channel: DirectoryChannel, cancellationToken: cancellationToken, handler: (directory) => { diff --git a/src/slskd/Shares/SharedFileCacheWorker.cs b/src/slskd/Shares/SharedFileCacheWorker.cs deleted file mode 100644 index 6ac5452b..00000000 --- a/src/slskd/Shares/SharedFileCacheWorker.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 System.Threading; - using System.Threading.Channels; - using System.Threading.Tasks; - using Serilog; - - /// - /// Shared file cache worker. - /// - public class SharedFileCacheWorker : ISharedFileCacheWorker - { - /// - /// Initializes a new instance of the class. - /// - /// The worker's unique Id. - /// The channel from which the worker will receive directories to scan. - /// A to monitor for cancellation requests. - /// An to be performed on each item read from the channel. - public SharedFileCacheWorker( - int id, - Channel directoryChannel, - CancellationToken cancellationToken, - Action handler) - { - Id = id; - DirectoryChannel = directoryChannel; - CancellationToken = cancellationToken; - Handler = handler; - } - - /// - /// Gets the that completes when the worker has completed all of its work. - /// - public Task Completed => TaskCompletionSource.Task; - - /// - /// Gets the Id of the worker. - /// - public int Id { get; } - - private Channel DirectoryChannel { get; } - private Action Handler { get; } - private TaskCompletionSource TaskCompletionSource { get; } = new TaskCompletionSource(); - private CancellationToken CancellationToken { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Starts the worker. - /// - public void Start() - { - _ = Read(); - Log.Debug("Shared file cache worker {Id} started", Id); - } - - private async Task Read() - { - try - { - while (!CancellationToken.IsCancellationRequested && !DirectoryChannel.Reader.Completion.IsCompleted) - { - var directory = await DirectoryChannel.Reader.ReadAsync(CancellationToken); - Handler(directory); - } - } - catch (ChannelClosedException) - { - // noop. the channel might close between the time we check and when we go to read; this just means there is no more data. - } - finally - { - Log.Debug($"Shared file cache worker {Id}'s work is complete.", Id); - TaskCompletionSource.SetResult(); - } - } - } -} -- cgit v1.2.3 From 270d10645a1725d67a4e14ab828451ec4c4d7338 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Sep 2022 13:29:35 -0500 Subject: bug --- src/slskd/Common/ChannelReader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/ChannelReader.cs b/src/slskd/Common/ChannelReader.cs index f358fb07..a6a8b9a3 100644 --- a/src/slskd/Common/ChannelReader.cs +++ b/src/slskd/Common/ChannelReader.cs @@ -114,7 +114,7 @@ namespace slskd.Shares { try { - while (Started && !CancellationTokenSource.Token.IsCancellationRequested && !Channel.Reader.Completion.IsCompleted) + while (!CancellationTokenSource.Token.IsCancellationRequested && !Channel.Reader.Completion.IsCompleted) { var item = await Channel.Reader.ReadAsync(CancellationToken); Handler(item); -- cgit v1.2.3