From 134333ac34716d539c4bd9ba438c0c829c23c810 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 Aug 2021 10:31:09 -0500 Subject: use a semaphore instead of a lock. add state changes and logging --- src/slskd/Application/Shares/SharedFileCache.cs | 74 ++++++++++++++++--------- 1 file changed, 48 insertions(+), 26 deletions(-) (limited to 'src/slskd/Application/Shares/SharedFileCache.cs') diff --git a/src/slskd/Application/Shares/SharedFileCache.cs b/src/slskd/Application/Shares/SharedFileCache.cs index 439e5eb8..e9bddb09 100644 --- a/src/slskd/Application/Shares/SharedFileCache.cs +++ b/src/slskd/Application/Shares/SharedFileCache.cs @@ -54,7 +54,7 @@ namespace slskd.Shares private IOptionsMonitor OptionsMonitor { get; set; } private SqliteConnection SQLite { get; set; } private IStateMonitor StateMonitor { get; set; } - private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private ILogger Log { get; } = Serilog.Log.ForContext(); /// @@ -63,11 +63,6 @@ namespace slskd.Shares /// The contents of the cache. public IEnumerable Browse() { - if (!StateMonitor.CurrentValue.Ready) - { - return Enumerable.Empty(); - } - var directories = new ConcurrentDictionary(); // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if @@ -109,7 +104,7 @@ namespace slskd.Shares /// The operation context. public async Task FillAsync() { - if (SyncRoot.TryEnterWriteLock(0)) + if (SyncRoot.CurrentCount == 0) { Log.Warning("Shared file scan rejected; scan is already in progress."); throw new ShareScanInProgressException("Shared files are already being scanned."); @@ -117,24 +112,38 @@ namespace slskd.Shares await Task.Yield(); - SyncRoot.EnterWriteLock(); + await SyncRoot.WaitAsync(); try { + StateMonitor.SetValue(state => state with { Filling = true, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + var sw = new Stopwatch(); sw.Start(); + var swSnapshot = 0L; - StateMonitor.SetValue(state => state with { Ready = false, FillProgress = 0 }); - + // this destroys the old table and creates a new one. empty the other cached fields to reflect this + // todo: use an A/B style table naming schema so that the cache remains available while it is filling CreateTable(); + Directories = new HashSet(); + Files = new Dictionary(); + StateMonitor.SetValue(state => state with { Directories = 0, Files = 0 }); + + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; var directories = OptionsMonitor.CurrentValue.Directories.Shared .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) .ToHashSet(); + StateMonitor.SetValue(state => state with { Directories = directories.Count }); + + Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting recursive scan.", sw.ElapsedMilliseconds - swSnapshot, directories.Count); + swSnapshot = sw.ElapsedMilliseconds; + var files = new Dictionary(); var current = 0; - var total = directories.Count; foreach (var directory in directories) { @@ -157,25 +166,49 @@ namespace slskd.Shares } current++; - StateMonitor.SetValue(state => state with { Ready = false, FillProgress = current / (double)total, Directories = current, Files = files.Count }); + StateMonitor.SetValue(state => state with { FillProgress = current / (double)directories.Count, Files = files.Count }); } + Log.Debug("Directory scan found {Files} in {Elapsed}ms. Populating filename database", files.Count, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite foreach (var file in files) { InsertFilename(file.Key); } + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + Directories = directories; Files = files; - StateMonitor.SetValue(state => state with { Ready = true, FillProgress = 1, Directories = directories.Count, Files = files.Count }); + StateMonitor.SetValue(state => state with + { + Filling = false, + Faulted = false, + FillProgress = 1, + Directories = Directories.Count, + Files = Files.Count, + }); + + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + StateMonitor.SetValue(state => state with + { + Filling = false, + Faulted = true, + FillProgress = 0, + }); - Log.Information($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}"); + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; } finally { - SyncRoot.ExitWriteLock(); + SyncRoot.Release(); } } @@ -186,11 +219,6 @@ namespace slskd.Shares /// The matching files. public async Task> SearchAsync(SearchQuery query) { - if (!StateMonitor.CurrentValue.Ready) - { - return Enumerable.Empty(); - } - // sanitize the query string. there's probably more to it than this. var text = query.Query .Replace("/", " ") @@ -200,8 +228,6 @@ namespace slskd.Shares var sql = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; - SyncRoot.EnterReadLock(); - try { using var cmd = new SqliteCommand(sql, SQLite); @@ -221,10 +247,6 @@ namespace slskd.Shares Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); return Enumerable.Empty(); } - finally - { - SyncRoot.ExitReadLock(); - } } private void CreateTable() -- cgit v1.2.3