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(+) 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 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(-) 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(-) 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(-) 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(-) 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 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 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(-) 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