diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-09-20 20:13:05 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-09-20 20:13:05 -0500 |
| commit | c4544a6a14577a79d02d009f38557cbcf9ec80ad (patch) | |
| tree | 69ae056823d2d5d050e2c80ff45b1ffa2126c1b4 /src | |
| parent | 2a1a7aca5f7a6fa70652135f7a7034bef55dfed4 (diff) | |
| parent | 6a307269ab99956fb2c5ea2149ae76c3ef24c8b2 (diff) | |
| download | slskd-c4544a6a14577a79d02d009f38557cbcf9ec80ad.tar.gz | |
Merge branch 'master' into aux/docs-proofreading
Diffstat (limited to 'src')
24 files changed, 1069 insertions, 369 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 04dbab2e..cab2b649 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -369,13 +369,22 @@ namespace slskd _ = CheckVersionAsync(); } - if (OptionsAtStartup.Flags.NoShareScan) + // 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.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(); + 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) + { + 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) @@ -411,14 +420,27 @@ namespace slskd private async Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) { Metrics.Browse.RequestsReceived.Inc(1); - + try { 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 + BrowseResponse response = default; + + var cacheFilename = Path.Combine(Program.DataDirectory, "browse.cache"); + var cacheFileInfo = new FileInfo(cacheFilename); + + if (!cacheFileInfo.Exists) + { + Log.Warning("Browse response not cached. Rebuilding..."); + await CacheBrowseResponse(); + } + + var stream = new FileStream(cacheFilename, FileMode.Open, FileAccess.Read); + response = new RawBrowseResponse(cacheFileInfo.Length, stream); + + Log.Information("Sent browse response to {User}", username); sw.Stop(); @@ -426,7 +448,7 @@ namespace slskd Metrics.Browse.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); Metrics.Browse.ResponsesSent.Inc(1); - return new BrowseResponse(directories); + return response; } catch (Exception ex) { @@ -758,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."); @@ -941,7 +963,7 @@ namespace slskd Client.Username, token, uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, - freeUploadSlots: forecastedPosition == 0 ? 1 : 0, + hasFreeUploadSlot: forecastedPosition == 0, queueLength: forecastedPosition, fileList: results); } @@ -967,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) { @@ -982,6 +1014,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; @@ -995,6 +1028,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("Share cache loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files); + _ = CacheBrowseResponse(); + } else { // the scan is neither starting nor finishing; progress update @@ -1009,6 +1049,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, "browse.cache"), response.ToByteArray()); + Log.Information("Browse response cached successfully"); + } + private void State_OnChange((State Previous, State Current) state) { _ = ApplicationHub.BroadcastStateAsync(state.Current); diff --git a/src/slskd/Common/ChannelReader.cs b/src/slskd/Common/ChannelReader.cs new file mode 100644 index 00000000..a6a8b9a3 --- /dev/null +++ b/src/slskd/Common/ChannelReader.cs @@ -0,0 +1,139 @@ +// <copyright file="ChannelReader.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Shares +{ + using System; + using System.Threading; + using System.Threading.Channels; + using System.Threading.Tasks; + + /// <summary> + /// Reads and handles items from a channel. + /// </summary> + public interface IChannelReader + { + /// <summary> + /// Gets the <see cref="Task"/> that completes when the reader has read all available items from the channel. + /// </summary> + Task Completed { get; } + + /// <summary> + /// Gets a value indicating whether the reader has started reading. + /// </summary> + bool Started { get; } + + /// <summary> + /// Starts the reader. + /// </summary> + void Start(); + } + + /// <summary> + /// Shared file cache worker. + /// </summary> + /// <typeparam name="T">The type of the underlying channel.</typeparam> + public class ChannelReader<T> : IChannelReader + { + /// <summary> + /// Initializes a new instance of the <see cref="ChannelReader"/> class. + /// </summary> + /// <param name="channel">The channel from which the reader will read.</param> + /// <param name="handler">An <see cref="Action"/> to be invoked for each item read from the channel.</param> + /// <param name="exceptionHandler">An optional <see cref="Action"/> to be invoked if the reader encounters an <see cref="Exception"/>.</param> + /// <param name="automaticallyStart">An optional value indicating whether to automatically start the reader.</param> + /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to monitor for cancellation.</param> + public ChannelReader( + Channel<T> channel, + Action<T> handler, + Action<Exception> exceptionHandler = null, + bool automaticallyStart = true, + CancellationToken cancellationToken = default) + { + Channel = channel; + Handler = handler; + ExceptionHandler = exceptionHandler; + + CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + CancellationToken = CancellationTokenSource.Token; + + if (automaticallyStart) + { + Start(); + } + } + + /// <summary> + /// Gets the <see cref="Task"/> that completes when the worker has completed all of its work. + /// </summary> + public Task Completed => TaskCompletionSource.Task; + + /// <summary> + /// Gets a value indicating whether the reader has started reading. + /// </summary> + public bool Started { get; private set; } + + private Channel<T> Channel { get; } + private Action<T> Handler { get; } + private Action<Exception> ExceptionHandler { get; } + private TaskCompletionSource TaskCompletionSource { get; } = new TaskCompletionSource(); + private CancellationTokenSource CancellationTokenSource { get; } + private CancellationToken CancellationToken { get; } + private object SyncRoot { get; } = new object(); + + /// <summary> + /// Starts the reader. + /// </summary> + public void Start() + { + lock (SyncRoot) + { + if (!Started) + { + _ = Read(); + Started = true; + } + } + } + + private async Task Read() + { + try + { + while (!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/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 65949016..9b6a3c6c 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -254,11 +254,21 @@ namespace slskd } /// <summary> - /// Converts the given path to the local format (normalizes path separators). + /// Converts the given path to the normalized format (normalizes path separators to backslashes). /// </summary> /// <param name="path">The path to convert.</param> /// <returns>The converted path.</returns> - public static string ToLocalOSPath(this string path) + public static string NormalizePath(this string path) + { + return path.Replace('/', '\\'); + } + + /// <summary> + /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). + /// </summary> + /// <param name="path">The path to convert.</param> + /// <returns>The converted path.</returns> + public static string LocalizePath(this string path) { return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); } @@ -278,7 +288,7 @@ namespace slskd } // normalize path separators - var localizedRemoteFilename = remoteFilename.ToLocalOSPath(); + var localizedRemoteFilename = remoteFilename.LocalizePath(); var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); @@ -350,6 +360,17 @@ namespace slskd } /// <summary> + /// Casts the string to <typeparamref name="T"/>. + /// </summary> + /// <typeparam name="T">The Enum type to which to cast.</typeparam> + /// <param name="str">The string to cast.</param> + /// <returns>The cast enum</returns> + public static T ToEnum<T>(this string str) + { + return (T)Enum.Parse(typeof(T), str, ignoreCase: true); + } + + /// <summary> /// Deserializes this string from json to an object of type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type to which to deserialize the string.</typeparam> 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 file="SqliteConnectionExtensions.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using Microsoft.Data.Sqlite; + + public static class SqliteConnectionExtensions + { + public static int ExecuteNonQuery(this SqliteConnection conn, string query, Action<SqliteCommand> action = null) + { + using var cmd = new SqliteCommand(query, conn); + action?.Invoke(cmd); + return cmd.ExecuteNonQuery(); + } + } +} diff --git a/src/slskd/Core/ConnectionStrings.cs b/src/slskd/Core/ConnectionStrings.cs new file mode 100644 index 00000000..6afab93f --- /dev/null +++ b/src/slskd/Core/ConnectionStrings.cs @@ -0,0 +1,30 @@ +// <copyright file="ConnectionStrings.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + /// <summary> + /// Application connection strings. + /// </summary> + public record ConnectionStrings + { + 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/Options.cs b/src/slskd/Core/Options.cs index 6a435db1..070476d1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -197,6 +197,12 @@ namespace slskd public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions(); /// <summary> + /// Gets share options. + /// </summary> + [Validate] + public SharesOptions Shares { get; init; } = new SharesOptions(); + + /// <summary> /// Gets global options. /// </summary> [Validate] @@ -324,7 +330,7 @@ namespace slskd /// <summary> /// Directory options. /// </summary> - public class DirectoriesOptions : IValidatableObject + public class DirectoriesOptions { /// <summary> /// Gets the path where incomplete downloads are saved. @@ -345,14 +351,60 @@ namespace slskd [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; + } + /// <summary> + /// Share options. + /// </summary> + public class SharesOptions : IValidatableObject + { /// <summary> /// Gets the list of paths to shared files. /// </summary> [Argument('s', "shared")] [EnvironmentVariable("SHARED_DIR")] - [Description("path to shared files")] - public string[] Shared { get; init; } = Array.Empty<string>(); + [Description("paths to shared files")] + public string[] Directories { get; init; } = Array.Empty<string>(); + + /// <summary> + /// Gets the list of shared file filters. + /// </summary> + [Argument(default, "share-filter")] + [EnvironmentVariable("SHARE_FILTER")] + [Description("regular expressions to filter files from shares")] + public string[] Filters { get; init; } = Array.Empty<string>(); + + /// <summary> + /// Share caching options. + /// </summary> + [Validate] + public ShareCacheOptions Cache { get; init; } = new ShareCacheOptions(); + + /// <summary> + /// Share caching options. + /// </summary> + public class ShareCacheOptions + { + /// <summary> + /// Gets the type of storage to use for the share cache. + /// </summary> + [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(); + + /// <summary> + /// Gets the number of workers to use while scanning shares. + /// </summary> + [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; + } /// <summary> /// Extended validation. @@ -363,17 +415,27 @@ namespace slskd { var results = new List<ValidationResult>(); - bool IsBlankPath(string share) => Regex.IsMatch(share.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])$"); - Shared.Where(share => IsBlankPath(share)).ToList() + results.AddRange(ValidateShares()); + results.AddRange(ValidateFilters()); + + return results; + } + + private IEnumerable<ValidationResult> ValidateShares() + { + var results = new List<ValidationResult>(); + + bool IsBlankPath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])$"); + 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.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])/$"); - Shared.Where(share => IsRootMount(share)).ToList() + bool IsRootMount(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])/$"); + 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.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); - Shared.Where(share => !IsAbsolutePath(share)).ToList() + bool IsAbsolutePath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); + 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 +450,7 @@ namespace slskd return (share, share.Split(new[] { '/', '\\' }).Last(), share); } - var digestedShared = Shared + var digestedShared = Directories .Select(share => Digest(share.TrimEnd('/', '\\'))) .ToHashSet(); @@ -415,6 +477,21 @@ namespace slskd return results; } + + private IEnumerable<ValidationResult> ValidateFilters() + { + var results = new List<ValidationResult>(); + + foreach (var filter in Filters) + { + if (!filter.IsValidRegex()) + { + results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); + } + } + + return results; + } } /// <summary> @@ -642,43 +719,15 @@ namespace slskd /// <summary> /// Filter options. /// </summary> - public class FiltersOptions : IValidatableObject + public class FiltersOptions { /// <summary> - /// Gets the list of shared file filters. - /// </summary> - [Argument(default, "share-filter")] - [EnvironmentVariable("SHARE_FILTER")] - [Description("regular expressions to filter files from shares")] - public string[] Share { get; init; } = Array.Empty<string>(); - - /// <summary> /// Gets search filter options. /// </summary> [Validate] public SearchOptions Search { get; init; } = new SearchOptions(); /// <summary> - /// Extended validation. - /// </summary> - /// <param name="validationContext"></param> - /// <returns></returns> - public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) - { - var results = new List<ValidationResult>(); - - foreach (var filter in Share) - { - if (!filter.IsValidRegex()) - { - results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); - } - } - - return results; - } - - /// <summary> /// Search filter options. /// </summary> public class SearchOptions : IValidatableObject @@ -755,12 +804,12 @@ namespace slskd /// Gets metrics endpoint authentication options. /// </summary> [Validate] - public AuthenticationOptions Authentication { get; init; } = new AuthenticationOptions(); + public MetricsAuthenticationOptions Authentication { get; init; } = new MetricsAuthenticationOptions(); /// <summary> /// Metrics endpoint authentication options. /// </summary> - public class AuthenticationOptions + public class MetricsAuthenticationOptions { /// <summary> /// Gets a value indicating whether authentication should be disabled. @@ -1114,12 +1163,12 @@ namespace slskd /// Gets authentication options. /// </summary> [Validate] - public AuthenticationOptions Authentication { get; init; } = new AuthenticationOptions(); + public WebAuthenticationOptions Authentication { get; init; } = new WebAuthenticationOptions(); /// <summary> /// Authentication options. /// </summary> - public class AuthenticationOptions + public class WebAuthenticationOptions { /// <summary> /// Gets a value indicating whether authentication should be disabled. 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; } 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 file="StorageMode.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + /// <summary> + /// Storage mode. + /// </summary> + public enum StorageMode + { + /// <summary> + /// Stored in memory. + /// </summary> + Memory = 0, + + /// <summary> + /// Stored on disk. + /// </summary> + Disk = 1, + } +} 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<FtpEncryptionMode>(); 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 diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 541f0f00..e828f242 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; @@ -161,6 +160,16 @@ namespace slskd public static string ConfigurationFile { get; private set; } = null; /// <summary> + /// Gets the connection strings for application databases. + /// </summary> + public static ConnectionStrings ConnectionStrings { get; private set; } = null; + + /// <summary> + /// Gets the path where persistent data is saved. + /// </summary> + public static string DataDirectory { get; private set; } = null; + + /// <summary> /// Gets the default fully qualified path to the configuration file. /// </summary> public static string DefaultConfigurationFile { get; private set; } @@ -246,6 +255,7 @@ namespace slskd // 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"); DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml"); DefaultDownloadsDirectory = Path.Combine(AppDirectory, "downloads"); @@ -260,7 +270,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); } @@ -323,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>() == StorageMode.Disk) + { + Log.Information("Using on-disk shared file cache"); + shareDbDataSource = Path.Combine(DataDirectory, "shares.db"); + } + else + { + Log.Information("Using in-memory shared file cache"); + shareDbDataSource = "file:shares?mode=memory"; + } + + ConnectionStrings = new() + { + Search = $"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;", + Transfers = $"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;", + Shares = $"Data Source={shareDbDataSource};Cache=shared", + SharesBackup = $"Data Source={Path.Combine(DataDirectory, "shares.db.bak")};", + }; + if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); @@ -447,10 +484,8 @@ namespace slskd services.AddSingleton<IConnectionWatchdog, ConnectionWatchdog>(); - ConfigureSQLite(); - - services.AddDbContext<SearchDbContext>("search.db"); - services.AddDbContext<TransfersDbContext>("transfers.db"); + services.AddDbContext<SearchDbContext>(ConnectionStrings.Search); + services.AddDbContext<TransfersDbContext>(ConnectionStrings.Transfers); services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IConversationTracker, ConversationTracker>(); @@ -474,7 +509,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(). @@ -512,7 +547,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 +873,7 @@ namespace slskd commandLine: Environment.CommandLine); } - private static IServiceCollection AddDbContext<T>(this IServiceCollection services, string filename) + private static IServiceCollection AddDbContext<T>(this IServiceCollection services, string connectionString) where T : DbContext { Log.Debug("Initializing database context {Name}", typeof(T).Name); @@ -847,7 +882,7 @@ namespace slskd { services.AddDbContextFactory<T>(options => { - options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)};Cache=shared;Pooling=True;"); + options.UseSqlite(connectionString); if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) { 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 @@ -46,12 +46,6 @@ namespace slskd.Search.API public int? MaximumPeerQueueLength { get; set; } /// <summary> - /// Gets or sets the minimum number of free upload slots a peer must have in order for a response to be processed. - /// (Default = 0). - /// </summary> - public int? MinimumPeerFreeUploadSlots { get; set; } - - /// <summary> /// Gets or sets the minimum upload speed a peer must have in order for a response to be processed. (Default = 0). /// </summary> public int? MinimumPeerUploadSpeed { get; set; } @@ -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<Soulseek.File, bool> 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); } /// <summary> 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<File> Files { get; init; } = new List<File>(); - public int FreeUploadSlots { get; init; } + public bool HasFreeUploadSlot { get; init; } public int LockedFileCount { get; init; } public ICollection<File> LockedFiles { get; init; } = new List<File>(); 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/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 16f1a890..962d4c1e 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/. // </copyright> +using System.IO; + namespace slskd.Shares { using System.Collections.Generic; @@ -58,7 +60,7 @@ namespace slskd.Shares /// <exception cref="NotFoundException"> /// Thrown when the specified remote filename can not be associated with a configured share. /// </exception> - Task<string> ResolveFilenameAsync(string remoteFilename); + Task<FileInfo> ResolveFileAsync(string remoteFilename); /// <summary> /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. @@ -73,5 +75,11 @@ namespace slskd.Shares /// <returns>The operation context.</returns> /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception> Task StartScanAsync(); + + /// <summary> + /// Attempt to load shares from disk. + /// </summary> + /// <returns>A value indicating whether shares were loaded.</returns> + Task<bool> TryLoadFromDiskAsync(); } -} +}
\ No newline at end of file diff --git a/src/slskd/Shares/ISharedFileCache.cs b/src/slskd/Shares/ISharedFileCache.cs new file mode 100644 index 00000000..52c7783c --- /dev/null +++ b/src/slskd/Shares/ISharedFileCache.cs @@ -0,0 +1,80 @@ +// <copyright file="ISharedFileCache.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Shares +{ + using System.Collections.Generic; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Soulseek; + + /// <summary> + /// Shared file cache. + /// </summary> + public interface ISharedFileCache + { + /// <summary> + /// Gets the cache state monitor. + /// </summary> + IStateMonitor<SharedFileCacheState> StateMonitor { get; } + + /// <summary> + /// Returns the contents of the cache. + /// </summary> + /// <returns>The contents of the cache.</returns> + IEnumerable<Directory> Browse(); + + /// <summary> + /// Scans the configured shares and fills the cache. + /// </summary> + /// <remarks>Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete.</remarks> + /// <param name="shares">The list of shares from which to fill the cache.</param> + /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> + /// <param name="cancellationToken">The optional cancellation token to monitor.</param> + /// <returns>The operation context.</returns> + Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters, CancellationToken cancellationToken = default); + + /// <summary> + /// Returns the contents of the specified <paramref name="directory"/>. + /// </summary> + /// <param name="directory">The directory for which the contents are to be listed.</param> + /// <returns>The contents of the directory.</returns> + Directory List(string directory); + + /// <summary> + /// Substitutes the mask in the specified <paramref name="filename"/> with the original path, if the mask is tracked + /// by the cache. + /// </summary> + /// <param name="filename">The fully qualified filename to unmask.</param> + /// <returns>The unmasked filename.</returns> + public string Resolve(string filename); + + /// <summary> + /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. + /// </summary> + /// <param name="query">The query for which to search.</param> + /// <returns>The matching files.</returns> + IEnumerable<File> Search(SearchQuery query); + + /// <summary> + /// Attempts to load the cache from disk. + /// </summary> + /// <returns>A value indicating whether the load was successful.</returns> + bool TryLoad(); + } +} diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 60fbdda3..96ac4c1c 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/. // </copyright> +using System.IO; using Microsoft.Extensions.Options; namespace slskd.Shares @@ -40,7 +41,10 @@ namespace slskd.Shares IOptionsMonitor<Options> optionsMonitor, ISharedFileCache sharedFileCache = null) { - Cache = sharedFileCache ?? new SharedFileCache(); + Cache = sharedFileCache ?? new SharedFileCache( + storageMode: optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum<StorageMode>(), + workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers); + Cache.StateMonitor.OnChange(cacheState => { var (previous, current) = cacheState; @@ -51,6 +55,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, @@ -86,7 +91,12 @@ namespace slskd.Shares /// </summary> /// <returns>The entire contents of the share.</returns> public Task<IEnumerable<Directory>> 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); + } /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. @@ -94,7 +104,12 @@ namespace slskd.Shares /// <param name="directory">The directory for which the contents are to be listed.</param> /// <returns>The contents of the directory.</returns> public Task<Directory> 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); + } /// <summary> /// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a @@ -105,16 +120,25 @@ namespace slskd.Shares /// <exception cref="NotFoundException"> /// Thrown when the specified remote filename can not be associated with a configured share. /// </exception> - public Task<string> ResolveFilenameAsync(string remoteFilename) + public Task<FileInfo> 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); } /// <summary> @@ -123,7 +147,16 @@ namespace slskd.Shares /// <param name="query">The query for which to search.</param> /// <returns>The matching files.</returns> public Task<IEnumerable<File>> SearchAsync(SearchQuery query) - => Cache.SearchAsync(query); + { + var results = Cache.Search(query); + + return Task.FromResult(results.Select(r => new File( + r.Code, + r.Filename.NormalizePath(), + r.Size, + r.Extension, + r.Attributes))); + } /// <summary> /// Starts a scan of the configured shares. @@ -131,7 +164,18 @@ namespace slskd.Shares /// <returns>The operation context.</returns> /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception> public Task StartScanAsync() - => Cache.FillAsync(Shares, FilterRegexes); + { + return Cache.FillAsync(Shares, FilterRegexes); + } + + /// <summary> + /// Attempt to load shares from disk. + /// </summary> + /// <returns>A value indicating whether shares were loaded.</returns> + public Task<bool> TryLoadFromDiskAsync() + { + return Task.FromResult(Cache.TryLoad()); + } private void Configure(Options options) { @@ -139,21 +183,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 6e38ee31..4afbfed8 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -22,10 +22,12 @@ 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; using System.Threading; + using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using Serilog; @@ -34,62 +36,18 @@ namespace slskd.Shares /// <summary> /// Shared file cache. /// </summary> - public interface ISharedFileCache - { - /// <summary> - /// Gets the cache state monitor. - /// </summary> - IStateMonitor<SharedFileCacheState> StateMonitor { get; } - - /// <summary> - /// Returns the contents of the cache. - /// </summary> - /// <returns>The contents of the cache.</returns> - IEnumerable<Directory> Browse(); - - /// <summary> - /// Scans the configured shares and fills the cache. - /// </summary> - /// <remarks>Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete.</remarks> - /// <param name="shares">The list of shares from which to fill the cache.</param> - /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> - /// <returns>The operation context.</returns> - Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters); - - /// <summary> - /// Returns the contents of the specified <paramref name="directory"/>. - /// </summary> - /// <param name="directory">The directory for which the contents are to be listed.</param> - /// <returns>The contents of the directory.</returns> - Directory List(string directory); - - /// <summary> - /// Substitutes the mask in the specified <paramref name="filename"/> with the original path, if the mask is tracked - /// by the cache. - /// </summary> - /// <param name="filename">The fully qualified filename to unmask.</param> - /// <returns>The unmasked filename.</returns> - public string Resolve(string filename); - - /// <summary> - /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. - /// </summary> - /// <param name="query">The query for which to search.</param> - /// <returns>The matching files.</returns> - Task<IEnumerable<File>> SearchAsync(SearchQuery query); - } - - /// <summary> - /// Shared file cache. - /// </summary> public class SharedFileCache : ISharedFileCache { /// <summary> /// Initializes a new instance of the <see cref="SharedFileCache"/> class. /// </summary> + /// <param name="storageMode"></param> + /// <param name="workerCount"></param> /// <param name="soulseekFileFactory"></param> - public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null) + public SharedFileCache(StorageMode storageMode, int workerCount, ISoulseekFileFactory soulseekFileFactory = null) { + StorageMode = storageMode; + WorkerCount = workerCount; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); } @@ -98,14 +56,14 @@ namespace slskd.Shares /// </summary> public IStateMonitor<SharedFileCacheState> StateMonitor => State; + private StorageMode StorageMode { get; } + private int WorkerCount { get; } private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>(); - private HashSet<string> MaskedDirectories { get; set; } - private Dictionary<string, File> MaskedFiles { get; set; } private List<Share> Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } - private SqliteConnection SQLite { get; set; } private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + private Channel<string> DirectoryChannel { get; set; } /// <summary> /// Returns the contents of the cache. @@ -130,23 +88,43 @@ 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 - .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Directory(g.Key, g.Select(g => + var files = new List<File>(); + + using var conn = GetConnection(); + 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()) + { + 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<List<FileAttribute>>(); + + var file = new File(code, filename, size, extension, attributeList); + + files.Add(file); + } + + var groups = files + .GroupBy(file => Path.GetDirectoryName(file.Filename)) + .Select(group => new Directory(group.Key, group.Select(f => { - 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); - }))); + }).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. @@ -155,7 +133,7 @@ namespace slskd.Shares directories.AddOrUpdate(group.Name, group, (_, _) => group); } - return directories.Values.OrderBy(f => f.Name); + return directories.Values.OrderBy(d => d.Name); } /// <summary> @@ -164,7 +142,7 @@ namespace slskd.Shares /// <param name="shares">The list of shares from which to fill the cache.</param> /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> /// <returns>The operation context.</returns> - public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters) + public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> 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)) @@ -175,19 +153,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(); @@ -210,9 +193,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 => { @@ -244,92 +227,120 @@ 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<string, File>(); var maskedDirectories = new HashSet<string>(); - var current = 0L; - var filtered = 0L; + var current = 0; + var cached = 0; + var filtered = 0; - foreach (var directory in unmaskedDirectories) + // set up a channel to fan out for directory scanning + DirectoryChannel = Channel.CreateBounded<string>(new BoundedChannelOptions(1000) { - Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count); + AllowSynchronousContinuations = false, + FullMode = BoundedChannelFullMode.Wait, + SingleReader = false, + SingleWriter = true, + }); - var addedFiles = 0L; - var filteredFiles = 0L; + // create workers to perform the fan out + var workers = new List<ChannelReader<string>>(); - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + foreach (var id in Enumerable.Range(0, WorkerCount)) + { + workers.Add(new ChannelReader<string>( + channel: DirectoryChannel, + cancellationToken: cancellationToken, + handler: (directory) => + { + Log.Debug("Starting scan of {Directory} ({Current}/{Total})", directory, current + 1, unmaskedDirectories.Count); - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + var addedFiles = 0; + var filteredFiles = 0; - // 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, - }) - .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) - .ToDictionary(file => file.Filename, file => file); - - 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) - { - if (filters.Any(filter => filter.IsMatch(file.Key))) + 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 + try { - filteredFiles++; - continue; + // 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.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. + 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); + } } - - if (files.ContainsKey(file.Key)) + catch (Exception ex) { - 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?)."); + 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); } - files[file.Key] = file.Value; - } - } - 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; + 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 = files.Count }); - } - 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("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; + Log.Debug("Starting workers..."); + workers.ForEach(w => w.Start()); + Log.Debug("All workers started"); - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) + Log.Debug("Filling DirectoryChannel..."); + foreach (var directory in unmaskedDirectories) { - InsertFilename(file.Key); + await DirectoryChannel.Writer.WriteAsync(directory); } - Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + 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"); - MaskedDirectories = maskedDirectories; - MaskedFiles = files; + 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); + + Log.Debug("Backing up shared file cache database..."); + Backup(); + Log.Debug("Shared file cache database backup complete"); State.SetValue(state => state with { @@ -337,11 +348,11 @@ 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}"); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {cached}"); } catch (Exception ex) { @@ -372,17 +383,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); } @@ -394,37 +395,19 @@ namespace slskd.Shares /// <returns>The unmasked filename.</returns> public string Resolve(string filename) { - filename = filename.ToLocalOSPath(); + using var conn = GetConnection(); + using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn); + cmd.Parameters.AddWithValue("maskedFilename", 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[] { '/', '\\' }); + var reader = cmd.ExecuteReader(); - if (parts.Length < 2) + if (!reader.Read()) { - Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); + Log.Warning("Failed to resolve shared file {Filename}", filename); return null; } - // find the share with a matching mask and alias/local directory - var share = Shares.FirstOrDefault(share => share.Alias == parts[0]); - - if (share == default) - { - Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from alias '{Alias}'", filename, parts[0]); - 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; } @@ -434,7 +417,7 @@ namespace slskd.Shares /// </summary> /// <param name="query">The query for which to search.</param> /// <returns>The matching files.</returns> - public async Task<IEnumerable<File>> SearchAsync(SearchQuery query) + public IEnumerable<File> Search(SearchQuery query) { if (!State.CurrentValue.Filled) { @@ -450,66 +433,286 @@ 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 results = new List<string>(); + 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)}' " + + "ORDER BY filenames.maskedFilename ASC;"; + + var results = new List<File>(); + SqliteDataReader reader = default; try { - using var conn = new SqliteConnection($"Data Source={Path.Combine(Program.AppDirectory, "data", "shares.db")};cache=shared"); + 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<List<FileAttribute>>(); + + var file = new File(code, filename, size, extension, attributeList); + results.Add(file); } + + return results; } catch (Exception ex) { Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); return Enumerable.Empty<File>(); } + } + /// <summary> + /// Attempts to load the cache from disk. + /// </summary> + /// <returns>A value indicating whether the load was successful.</returns> + public bool TryLoad() + { try { - return results.Select(r => MaskedFiles[r]).ToList(); + // 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 (!ValidateTables(Program.ConnectionStrings.SharesBackup)) + { + Log.Debug("Share cache backup is missing; unable to restore"); + return false; + } + + 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"); + } + + // 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, + Faulted = false, + Filled = true, + FillProgress = 1, + Directories = CountDirectories(), + Files = CountFiles(), + }); + + return true; } catch (Exception ex) { - Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); - return Enumerable.Empty<File>(); + Log.Debug(ex, "Error loading shared file cache: {Message}", ex.Message); + return false; } } - private void CreateTable() + private bool ValidateTables(string connectionString) { - if (SQLite != null) + var schema = new Dictionary<string, string>() { - SQLite.Dispose(); + { "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 (rows != schema.Count) + { + throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}"); + } + + return true; + } + catch (Exception ex) + { + Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); + return false; } + } + + private void Backup() + { + using var sourceConn = GetConnection(); + using var backupConn = GetConnection(Program.ConnectionStrings.SharesBackup); + sourceConn.BackupDatabase(backupConn); + } + + 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(); - SQLite = new SqliteConnection($"Data Source={Path.Combine(Program.AppDirectory, "data", "shares.db")};cache=shared"); - SQLite.Open(); + conn.ExecuteNonQuery("DROP TABLE IF EXISTS directories; CREATE TABLE directories (name TEXT PRIMARY KEY);"); + + conn.ExecuteNonQuery("DROP TABLE IF EXISTS filenames; CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename);"); + + 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);"); + } - using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); - cmd.ExecuteNonQuery(); + private SqliteConnection GetConnection(string connectionString = null) + { + var conn = new SqliteConnection(connectionString ?? Program.ConnectionStrings.Shares); + conn.Open(); + return conn; + } + + private void InsertDirectory(string name) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("INSERT INTO directories VALUES(@name) ON CONFLICT DO NOTHING;", cmd => + { + cmd.Parameters.AddWithValue("name", name); + }); } - private void InsertFilename(string filename) + private void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file) { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES(@filename)", SQLite); - cmd.Parameters.AddWithValue("filename", filename); - cmd.ExecuteNonQuery(); + 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 void ResetCache() + private IEnumerable<string> ListDirectories() { - CreateTable(); - MaskedDirectories = new HashSet<string>(); - MaskedFiles = new Dictionary<string, File>(); - State.SetValue(state => state with { Directories = 0, Files = 0 }); + var results = new List<string>(); + + using var conn = GetConnection(); + + using var cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results; + } + + private IEnumerable<File> ListFiles(string directory = null) + { + var results = new List<File>(); + + SqliteCommand cmd = default; + using var conn = GetConnection(); + + try + { + if (string.IsNullOrEmpty(directory)) + { + 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 ORDER BY maskedFilename ASC;", conn); + 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); + + var attributeList = attributeJson.FromJson<List<FileAttribute>>(); + + var file = new File(code, filename: Path.GetFileName(filename), size, extension, attributeList); + + results.Add(file); + } + + return results; + } + finally + { + cmd?.Dispose(); + } } } }
\ No newline at end of file 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/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs index 5696b0f1..3a000a52 100644 --- a/src/slskd/Transfers/Types/UploadGroup.cs +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -17,9 +17,9 @@ namespace slskd.Transfers { - public sealed class UploadGroup + public sealed record UploadGroup { - public string Name { get; set; } + public string Name { get; init; } public int Priority { get; set; } public bool SlotAvailable => UsedSlots < Slots; public int Slots { get; set; } diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 36e5474c..2c7e3eac 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -105,11 +105,11 @@ namespace slskd.Transfers Configure(OptionsMonitor.CurrentValue); } + private int GlobalSlots { get; set; } = 0; private Dictionary<string, UploadGroup> Groups { get; set; } = new Dictionary<string, UploadGroup>(); private int LastGlobalSlots { get; set; } private string LastOptionsHash { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext<UploadQueue>(); - private int MaxSlots { get; set; } = 0; private IOptionsMonitor<Options> OptionsMonitor { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private ConcurrentDictionary<string, List<Upload>> Uploads { get; set; } = new ConcurrentDictionary<string, List<Upload>>(); @@ -378,7 +378,7 @@ namespace slskd.Transfers return; } - MaxSlots = options.Global.Upload.Slots; + GlobalSlots = options.Global.Upload.Slots; // statically add built-in groups var groups = new List<UploadGroup>() @@ -392,7 +392,7 @@ namespace slskd.Transfers { Name = Application.PrivilegedGroup, Priority = 0, - Slots = MaxSlots, + Slots = GlobalSlots, UsedSlots = GetExistingUsedSlotsOrDefault(Application.PrivilegedGroup), Strategy = QueueStrategy.FirstInFirstOut, }, @@ -400,17 +400,17 @@ 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), + Strategy = options.Groups.Default.Upload.Strategy.ToEnum<QueueStrategy>(), }, new UploadGroup() { 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), + Strategy = options.Groups.Leechers.Upload.Strategy.ToEnum<QueueStrategy>(), }, }; @@ -419,9 +419,9 @@ 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), + Strategy = kvp.Value.Upload.Strategy.ToEnum<QueueStrategy>(), })); Groups = groups.ToDictionary(g => g.Name); @@ -442,7 +442,11 @@ namespace slskd.Transfers try { - if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) + // 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; } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 740c6237..c3cfe2fb 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -107,21 +107,13 @@ namespace slskd.Transfers.Uploads /// <returns>The operation context.</returns> 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)).ToLocalOSPath(); - - 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, @@ -166,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 { @@ -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) { @@ -236,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; } @@ -258,7 +250,7 @@ namespace slskd.Transfers.Uploads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, cancellable: false); throw; } diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 8f0f99b2..f35a6485 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,7 @@ <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Soulseek" Version="5.1.1" /> + <PackageReference Include="Soulseek" Version="5.1.5" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> 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; |
