diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-09-22 08:51:54 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-09-22 08:51:54 -0500 |
| commit | 26ac1164d581ae2a9fc5d195d32b42e2cbb954d0 (patch) | |
| tree | 93eb96ac9fa4cc99ce6783d97df73c2ddda93d2a /src | |
| parent | 9bb986d218c1e56a988e25dc92b0778471788f50 (diff) | |
| parent | a860ffdf0a6f016eee88859728db552c42c63233 (diff) | |
| download | slskd-26ac1164d581ae2a9fc5d195d32b42e2cbb954d0.tar.gz | |
Merge pull request #653 from slskd/in-place-scan
Update existing shared file database instead of creating a new one for each scan
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 14 | ||||
| -rw-r--r-- | src/slskd/Shares/SharedFileCache.cs | 134 |
2 files changed, 79 insertions, 69 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index cab2b649..20735ead 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -29,8 +29,8 @@ namespace slskd using System.Net.Sockets; using System.Reflection; using System.Runtime; - using System.Text.RegularExpressions; using System.Runtime.InteropServices; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; @@ -383,6 +383,7 @@ namespace slskd } else { + // todo: should this be forced prior to connection if the cache can't be loaded? _ = Shares.StartScanAsync(); } } @@ -989,17 +990,8 @@ namespace slskd SharesRefreshStarted = DateTime.UtcNow; State.SetValue(s => s with { Shares = current }); - Log.Information("Share scan started"); - try - { - System.IO.File.Delete(Path.Combine(Program.DataDirectory, "browse.cache")); - Log.Information("Cleared browse response cache"); - } - catch - { - // noop - } + Log.Information("Share scan started"); } else if (previous.Scanning && !current.Scanning) { diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 4afbfed8..6967e44a 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -71,16 +71,6 @@ namespace slskd.Shares /// <returns>The contents of the cache.</returns> public IEnumerable<Directory> Browse() { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; - } - - return Enumerable.Empty<Directory>(); - } - var directories = new ConcurrentDictionary<string, Directory>(); // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if @@ -141,6 +131,7 @@ namespace slskd.Shares /// </summary> /// <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 for cancellation requests.</param> /// <returns>The operation context.</returns> public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters, CancellationToken cancellationToken = default) { @@ -153,10 +144,6 @@ 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, @@ -167,10 +154,21 @@ namespace slskd.Shares ExcludedDirectories = 0, }); + // it's possible that the database was tampered with between the time it was checked at startup and now + // validate the tables, and if there's an issue, drop and recreate everything. + if (!ValidateTables(Program.ConnectionStrings.Shares)) + { + Log.Warning("Shared file cache invalid; dropping and re-creating prior to scan."); + CreateTables(discardExisting: true); + Log.Information("Share file cache ready."); + } + Log.Debug("Starting shared file scan"); await Task.Yield(); + var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var sw = new Stopwatch(); var swSnapshot = 0L; sw.Start(); @@ -190,7 +188,7 @@ namespace slskd.Shares Shares.Where(s => s.IsExcluded).ToList() .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); - Log.Debug("Enumerating shared directories"); + Log.Information("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 @@ -224,10 +222,9 @@ namespace slskd.Shares unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); - Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); + Log.Information("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 maskedDirectories = new HashSet<string>(); var current = 0; var cached = 0; var filtered = 0; @@ -258,8 +255,7 @@ namespace slskd.Shares var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); - InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath), timestamp); // 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 @@ -289,7 +285,7 @@ namespace slskd.Shares continue; } - InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file); + InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file, timestamp); } } catch (Exception ex) @@ -333,10 +329,13 @@ namespace slskd.Shares 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", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); + Log.Information("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); + var deletedFiles = DeleteStaleFiles(timestamp); + var deletedDirectories = DeleteStaleDirectories(timestamp); + + Log.Information("Removed or renamed {Files} files and {Directories} directories in {Elapsed}ms", deletedFiles, deletedDirectories, sw.ElapsedMilliseconds - swSnapshot); Log.Debug("Backing up shared file cache database..."); Backup(); @@ -373,16 +372,6 @@ namespace slskd.Shares /// <returns>The contents of the directory.</returns> public Directory List(string directory) { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); - } - - return null; - } - var files = ListFiles(directory); return new Directory(directory, files); } @@ -419,11 +408,6 @@ namespace slskd.Shares /// <returns>The matching files.</returns> public IEnumerable<File> Search(SearchQuery query) { - if (!State.CurrentValue.Filled) - { - return Enumerable.Empty<File>(); - } - string Clean(string str) => str.Replace("/", " ") .Replace("\\", " ") .Replace(":", " ") @@ -523,13 +507,31 @@ namespace slskd.Shares } } + private void CreateTables(bool discardExisting = false) + { + using var conn = GetConnection(); + + if (discardExisting) + { + conn.ExecuteNonQuery("DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;"); + } + + conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL);"); + + conn.ExecuteNonQuery("CREATE VIRTUAL TABLE IF NOT EXISTS filenames USING fts5(maskedFilename);"); + + conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS files " + + "(maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, " + + "extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL);"); + } + private bool ValidateTables(string connectionString) { var schema = new Dictionary<string, string>() { - { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY)" }, + { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, { "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)" }, + { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, }; try @@ -601,19 +603,6 @@ namespace slskd.Shares return reader.GetInt32(0); } - private void CreateTables() - { - using var conn = GetConnection(); - - 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);"); - } - private SqliteConnection GetConnection(string connectionString = null) { var conn = new SqliteConnection(connectionString ?? Program.ConnectionStrings.Shares); @@ -621,23 +610,38 @@ namespace slskd.Shares return conn; } - private void InsertDirectory(string name) + private void InsertDirectory(string name, long timestamp) { using var conn = GetConnection(); - conn.ExecuteNonQuery("INSERT INTO directories VALUES(@name) ON CONFLICT DO NOTHING;", cmd => + conn.ExecuteNonQuery("INSERT INTO directories VALUES(@name, @timestamp) ON CONFLICT DO UPDATE SET timestamp = excluded.timestamp;", cmd => { cmd.Parameters.AddWithValue("name", name); + cmd.Parameters.AddWithValue("timestamp", timestamp); }); } - private void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file) + private long DeleteStaleDirectories(long timestamp) + { + using var conn = GetConnection(); + + using var cmd = new SqliteCommand("DELETE FROM directories WHERE timestamp < @timestamp; SELECT changes()", conn); + cmd.Parameters.AddWithValue("timestamp", timestamp); + + var reader = cmd.ExecuteReader(); + reader.Read(); + + return reader.GetInt64(0); + } + + private void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp) { 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 => + conn.ExecuteNonQuery("INSERT INTO files (maskedFilename, originalFilename, size, touchedAt, code, extension, attributeJson, timestamp) " + + "VALUES(@maskedFilename, @originalFilename, @size, @touchedAt, @code, @extension, @attributeJson, @timestamp) " + + "ON CONFLICT DO UPDATE SET originalFilename = excluded.originalFilename, size = excluded.size, touchedAt = excluded.touchedAt, " + + "code = excluded.code, extension = excluded.extension, attributeJson = excluded.attributeJson, timestamp = excluded.timestamp;", cmd => { cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); cmd.Parameters.AddWithValue("originalFilename", originalFilename); @@ -646,6 +650,7 @@ namespace slskd.Shares cmd.Parameters.AddWithValue("code", file.Code); cmd.Parameters.AddWithValue("extension", file.Extension); cmd.Parameters.AddWithValue("attributeJson", file.Attributes.ToJson()); + cmd.Parameters.AddWithValue("timestamp", timestamp); }); conn.ExecuteNonQuery("INSERT INTO filenames (maskedFilename) VALUES(@maskedFilename);", cmd => @@ -654,6 +659,19 @@ namespace slskd.Shares }); } + private long DeleteStaleFiles(long timestamp) + { + using var conn = GetConnection(); + + using var cmd = new SqliteCommand("DELETE FROM files WHERE timestamp < @timestamp; SELECT changes()", conn); + cmd.Parameters.AddWithValue("timestamp", timestamp); + + var reader = cmd.ExecuteReader(); + reader.Read(); + + return reader.GetInt64(0); + } + private IEnumerable<string> ListDirectories() { var results = new List<string>(); |
