aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2023-12-29 15:24:27 -0600
committerGitHub <noreply@github.com>2023-12-29 15:24:27 -0600
commita116b66c581364b4f76ded1507867d6f6b336889 (patch)
treec802cfbd7cda54bb7466a01ebf791b5420f47557 /src
parent3ae7cfb73a365c876dfc600779d886ec9be2a944 (diff)
parentb40d5feb0617be45a5c5f5c96cca75695ebf41a3 (diff)
downloadslskd-a116b66c581364b4f76ded1507867d6f6b336889.tar.gz
Merge pull request #1032 from slskd/re-scan
Add a setting to re-scan shares on a regular interval (add retention limit to the cache)
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs38
-rw-r--r--src/slskd/Core/Options.cs9
-rw-r--r--src/slskd/Shares/IShareRepository.cs8
-rw-r--r--src/slskd/Shares/IShareService.cs52
-rw-r--r--src/slskd/Shares/ShareService.cs53
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs38
6 files changed, 158 insertions, 40 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 37bc4f78..5c926644 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -761,6 +761,44 @@ namespace slskd
private void Clock_EveryHour(object sender, ClockEventArgs e)
{
+ _ = Task.Run(() => MaybeRescanShares());
+ }
+
+ private async Task MaybeRescanShares()
+ {
+ // ignore this if we're already scanning. there are multiple safeguards using
+ // SemaphoreSlim later in the call chain if we manage to slip by somehow, though
+ if (Shares.StateMonitor.CurrentValue.Scanning)
+ {
+ return;
+ }
+
+ var ttl = Options.Shares.Cache.Retention;
+
+ // no configured TTL; never re-scan automatically
+ if (!ttl.HasValue)
+ {
+ return;
+ }
+
+ // "x minutes ago"
+ var cutoffTimestamp = DateTimeOffset.UtcNow
+ .AddMinutes(-ttl.Value)
+ .ToUnixTimeMilliseconds();
+
+ // get a list of all scans that 1) started after our cutoff timestamp
+ var scansInRange = await Shares.ListScansAsync(startedAtOrAfter: cutoffTimestamp);
+
+ // 2) that succeeded (have a valid EndedAt)
+ // and 3) have not been marked suspect
+ // if there's no scan that meets all 3 criteria, try to re-scan
+ if (!scansInRange.Any(s => s.EndedAt is not null && !s.Suspect))
+ {
+ Log.Information("Beginning scheduled re-scan of shares (previous scan is older than {Minutes} minutes)", ttl);
+
+ // fire and forget. if something slips through the underlying logic will log.
+ _ = Task.Run(() => Shares.ScanAsync());
+ }
}
private void PruneFiles()
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 077ecf74..94f8618d 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -752,6 +752,15 @@ namespace slskd
[Range(1, 128)]
[RequiresRestart]
public int Workers { get; init; } = Environment.ProcessorCount;
+
+ /// <summary>
+ /// Gets the time to retain the cache (the interval on which to re-scan automatically), in minutes.
+ /// </summary>
+ [Argument(default, "share-cache-retention")]
+ [EnvironmentVariable("SHARE_CACHE_RETENTION")]
+ [Description("the time to retain the cache (re-scan interval), in minutes")]
+ [Range(60, int.MaxValue)]
+ public int? Retention { get; init; } = null;
}
}
diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs
index f1e59889..41b0fe32 100644
--- a/src/slskd/Shares/IShareRepository.cs
+++ b/src/slskd/Shares/IShareRepository.cs
@@ -131,6 +131,14 @@ namespace slskd.Shares
IEnumerable<File> ListFiles(string parentDirectory = null, bool includeFullPath = false);
/// <summary>
+ /// Returns the list of all <see cref="Scan"/> started at or after the specified <paramref name="startedAtOrAfter"/>
+ /// unix timestamp.
+ /// </summary>
+ /// <param name="startedAtOrAfter">A unix timestamp that serves as the lower bound of the time-based listing.</param>
+ /// <returns>The operation context, including the list of found scans.</returns>
+ IEnumerable<Scan> ListScans(long startedAtOrAfter = 0);
+
+ /// <summary>
/// Deletes directory records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>.
/// </summary>
/// <param name="olderThanTimestamp">The timestamp before which to delete directories.</param>
diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs
index aea3240a..7e1352e9 100644
--- a/src/slskd/Shares/IShareService.cs
+++ b/src/slskd/Shares/IShareService.cs
@@ -61,12 +61,11 @@ namespace slskd.Shares
Task DumpAsync(string filename);
/// <summary>
- /// Returns the share host with the specified <paramref name="name"/>.
+ /// Initializes the service and shares.
/// </summary>
- /// <param name="name">The name of the host.</param>
- /// <param name="host">The host, if found.</param>
- /// <returns>A value indicating whether the host was found.</returns>
- bool TryGetHost(string name, out Host host);
+ /// <param name="forceRescan">A value indicating whether a full re-scan of shares should be performed.</param>
+ /// <returns>The operation context.</returns>
+ Task InitializeAsync(bool forceRescan = false);
/// <summary>
/// Returns the contents of the specified <paramref name="directory"/>.
@@ -76,11 +75,17 @@ namespace slskd.Shares
Task<Directory> ListDirectoryAsync(string directory);
/// <summary>
- /// Removes the share host with the specified <paramref name="name"/>.
+ /// Returns the list of all <see cref="Scan"/> started at or after the specified <paramref name="startedAtOrAfter"/>
+ /// unix timestamp.
/// </summary>
- /// <param name="name">The name of the host.</param>
- /// <returns>A value indicating whether the host was removed.</returns>
- bool TryRemoveHost(string name);
+ /// <param name="startedAtOrAfter">A unix timestamp that serves as the lower bound of the time-based listing.</param>
+ /// <returns>The operation context, including the list of found scans.</returns>
+ Task<IEnumerable<Scan>> ListScansAsync(long startedAtOrAfter = 0);
+
+ /// <summary>
+ /// Requests that a share scan is performed.
+ /// </summary>
+ void RequestScan();
/// <summary>
/// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a
@@ -94,9 +99,11 @@ namespace slskd.Shares
Task<(string Host, string Filename)> ResolveFileAsync(string remoteFilename);
/// <summary>
- /// Requests that a share scan is performed.
+ /// Scans the configured shares on the local host.
/// </summary>
- void RequestScan();
+ /// <returns>The operation context.</returns>
+ /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
+ Task ScanAsync();
/// <summary>
/// Searches the cache for the specified <paramref name="query"/> and returns the matching files.
@@ -106,23 +113,24 @@ namespace slskd.Shares
Task<IEnumerable<File>> SearchAsync(SearchQuery query);
/// <summary>
- /// Scans the configured shares on the local host.
- /// </summary>
- /// <returns>The operation context.</returns>
- /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
- Task ScanAsync();
-
- /// <summary>
/// Cancels the currently running scan on the local host, if one is running.
/// </summary>
/// <returns>A value indicating whether a scan was cancelled.</returns>
bool TryCancelScan();
/// <summary>
- /// Initializes the service and shares.
+ /// Returns the share host with the specified <paramref name="name"/>.
/// </summary>
- /// <param name="forceRescan">A value indicating whether a full re-scan of shares should be performed.</param>
- /// <returns>The operation context.</returns>
- Task InitializeAsync(bool forceRescan = false);
+ /// <param name="name">The name of the host.</param>
+ /// <param name="host">The host, if found.</param>
+ /// <returns>A value indicating whether the host was found.</returns>
+ bool TryGetHost(string name, out Host host);
+
+ /// <summary>
+ /// Removes the share host with the specified <paramref name="name"/>.
+ /// </summary>
+ /// <param name="name">The name of the host.</param>
+ /// <returns>A value indicating whether the host was removed.</returns>
+ bool TryRemoveHost(string name);
}
} \ No newline at end of file
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index bdc18859..97867cde 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -102,6 +102,7 @@ namespace slskd.Shares
private IShareRepositoryFactory ShareRepositoryFactory { get; }
private IShareScanner Scanner { get; }
+ private SemaphoreSlim ScannerSyncRoot { get; } = new SemaphoreSlim(1, 1);
private string LastOptionsHash { get; set; }
private IOptionsMonitor<Options> OptionsMonitor { get; }
private ConcurrentDictionary<string, (Host Host, IShareRepository Repository)> HostDictionary { get; set; } = new();
@@ -306,6 +307,15 @@ namespace slskd.Shares
}
/// <summary>
+ /// Returns the list of all <see cref="Scan"/> started at or after the specified <paramref name="startedAtOrAfter"/>
+ /// unix timestamp.
+ /// </summary>
+ /// <param name="startedAtOrAfter">A unix timestamp that serves as the lower bound of the time-based listing.</param>
+ /// <returns>The operation context, including the list of found scans.</returns>
+ public Task<IEnumerable<Scan>> ListScansAsync(long startedAtOrAfter = 0)
+ => Task.FromResult(Local.Repository.ListScans(startedAtOrAfter));
+
+ /// <summary>
/// Requests that a share scan is performed.
/// </summary>
public void RequestScan()
@@ -333,24 +343,39 @@ namespace slskd.Shares
/// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
public async Task ScanAsync()
{
- State.SetValue(state => state with { Ready = false });
+ // try to obtain the semaphore, or fail if it has already been obtained
+ // the scanner has an identical check, but because this method changes state we need it here, too
+ if (!await ScannerSyncRoot.WaitAsync(millisecondsTimeout: 0))
+ {
+ Log.Warning("Shared file scan rejected; scan is already in progress.");
+ throw new ShareScanInProgressException("Shared files are already being scanned.");
+ }
- await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares, Local.Repository);
+ try
+ {
+ State.SetValue(state => state with { Ready = false });
- Log.Debug("Backing up shared file cache database...");
- Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name));
- Log.Debug("Shared file cache database backup complete");
+ await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares, Local.Repository);
- Log.Debug("Recomputing share statistics...");
- ComputeShareStatistics();
- Log.Debug("Share statistics updated: {Shares}", Local.Host.Shares.ToJson());
+ Log.Debug("Backing up shared file cache database...");
+ Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name));
+ Log.Debug("Shared file cache database backup complete");
- State.SetValue(state => state with
+ Log.Debug("Recomputing share statistics...");
+ ComputeShareStatistics();
+ Log.Debug("Share statistics updated: {Shares}", Local.Host.Shares.ToJson());
+
+ State.SetValue(state => state with
+ {
+ Directories = Hosts.SelectMany(host => host.Shares).Sum(share => share.Directories ?? 0),
+ Files = Hosts.SelectMany(host => host.Shares).Sum(share => share.Files ?? 0),
+ Ready = true,
+ });
+ }
+ finally
{
- Directories = Hosts.SelectMany(host => host.Shares).Sum(share => share.Directories ?? 0 ),
- Files = Hosts.SelectMany(host => host.Shares).Sum(share => share.Files ?? 0),
- Ready = true,
- });
+ ScannerSyncRoot.Release();
+ }
}
/// <summary>
@@ -433,7 +458,7 @@ namespace slskd.Shares
var options = OptionsMonitor.CurrentValue.Shares;
var latestScan = Local.Repository.FindLatestScan();
- Log.Debug("Latest scan: {Scan}, current options {Options}", latestScan, options);
+ Log.Debug("Latest scan: {Scan}, current options {@Options}", latestScan, options);
if (latestScan == default)
{
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index f10b55e5..57a76177 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -38,11 +38,11 @@ namespace slskd.Shares
{
ConnectionString = connectionString;
- // in-memory databases will be destroyed if at any point the number of connections reaches zero to prevent this,
+ // in-memory databases will be destroyed if at any point the number of connections reaches zero. to prevent this,
// create a connection and hold it open for the duration of the application. SQLite will destroy this database when
- // the connection that created it closes. since this is the first connection, it *should* keep the db alive.
- // it's possible that this connection will be recycled somehow due to pooling; the app will crash if this happens
- // so i'll know to keep digging.
+ // the connection that created it closes. since this is the first connection, it *should* keep the db alive. it's
+ // possible that this connection will be recycled somehow due to pooling; the app will crash if this happens so i'll
+ // know to keep digging.
KeepaliveConnection = GetConnection(ConnectionString);
KeepaliveTimer = new Timer(1000)
{
@@ -420,6 +420,36 @@ namespace slskd.Shares
}
/// <summary>
+ /// Returns the list of all <see cref="Scan"/> started at or after the specified <paramref name="startedAtOrAfter"/>
+ /// unix timestamp.
+ /// </summary>
+ /// <param name="startedAtOrAfter">A unix timestamp that serves as the lower bound of the time-based listing.</param>
+ /// <returns>The operation context, including the list of found scans.</returns>
+ public IEnumerable<Scan> ListScans(long startedAtOrAfter = 0)
+ {
+ using var conn = GetConnection();
+ using var cmd = new SqliteCommand($"SELECT timestamp, options, COALESCE(end, -1), suspect FROM scans WHERE timestamp >= {startedAtOrAfter}", conn);
+
+ var reader = cmd.ExecuteReader();
+ var scans = new List<Scan>();
+
+ while (reader.Read())
+ {
+ var timestamp = reader.GetInt64(0);
+ var optionsJson = reader.GetString(1);
+
+ var endRaw = reader.GetInt64(2);
+ long? end = endRaw == -1 ? null : endRaw;
+
+ var suspect = reader.GetInt32(3) > 0;
+
+ scans.Add(new Scan { StartedAt = timestamp, OptionsJson = optionsJson, EndedAt = end, Suspect = suspect });
+ }
+
+ return scans;
+ }
+
+ /// <summary>
/// Deletes directory records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>.
/// </summary>
/// <param name="olderThanTimestamp">The timestamp before which to delete directories.</param>