aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Shares/ShareService.cs
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-10-14 08:41:12 -0500
committerGitHub <noreply@github.com>2022-10-14 08:41:12 -0500
commit593308d4e786cd569e3a683f5b02b8f13aa39b23 (patch)
tree3555863f90065a615ce4f59fcc58d7dcd818e8ed /src/slskd/Shares/ShareService.cs
parentdc1e6a63db9ff87813633963b2f3d7acc60d2709 (diff)
parentfe03a44d359e3bcd39447609a0aa15b8492e5306 (diff)
downloadslskd-593308d4e786cd569e3a683f5b02b8f13aa39b23.tar.gz
Merge pull request #695 from slskd/multi-shares
Refactor some internals to allow multiple share repositories to be used
Diffstat (limited to 'src/slskd/Shares/ShareService.cs')
-rw-r--r--src/slskd/Shares/ShareService.cs103
1 files changed, 76 insertions, 27 deletions
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index 098fa56c..12131eae 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -24,7 +24,6 @@ namespace slskd.Shares
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
- using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
@@ -38,16 +37,40 @@ namespace slskd.Shares
/// <summary>
/// Initializes a new instance of the <see cref="ShareService"/> class.
/// </summary>
+ /// <param name="shareConnectionStringFactory"></param>
/// <param name="optionsMonitor"></param>
/// <param name="scanner"></param>
public ShareService(
+ ShareConnectionStringFactory shareConnectionStringFactory,
IOptionsMonitor<Options> optionsMonitor,
IShareScanner scanner = null)
{
- CacheStorageMode = optionsMonitor.CurrentValue.Shares.Cache.StorageMode.ToEnum<StorageMode>();
+ var options = optionsMonitor.CurrentValue;
+
+ ConnectionStringFactory = shareConnectionStringFactory;
+ CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum<StorageMode>();
+
+ if (CacheStorageMode == StorageMode.Memory)
+ {
+ ConnectionString = ConnectionStringFactory.CreateFromMemory(options.InstanceName);
+ }
+ else
+ {
+ ConnectionString = ConnectionStringFactory.CreateFromFile(options.InstanceName);
+ }
+
+ BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile(options.InstanceName);
+
+ var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online);
+ var repository = new SqliteShareRepository(ConnectionString);
+
+ Local = (host, repository);
+
+ AllRepositories = new List<IShareRepository>(new[] { repository });
Scanner = scanner ?? new ShareScanner(
- workerCount: optionsMonitor.CurrentValue.Shares.Cache.Workers);
+ shareRepository: repository,
+ workerCount: options.Shares.Cache.Workers);
Scanner.StateMonitor.OnChange(cacheState =>
{
@@ -67,8 +90,6 @@ namespace slskd.Shares
});
});
- Repository = new ShareRepository(connectionString: Program.ConnectionStrings.Shares);
-
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
@@ -78,24 +99,45 @@ namespace slskd.Shares
}
/// <summary>
- /// Gets the list of configured shares.
+ /// Gets the list of share hosts.
/// </summary>
- public IReadOnlyList<Share> Shares => SharesList.AsReadOnly();
+ public IReadOnlyList<Host> Hosts => HostDictionary.Values.Select(v => v.Host).Prepend(Local.Host).ToList().AsReadOnly();
/// <summary>
/// Gets the state monitor for the service.
/// </summary>
public IStateMonitor<ShareState> StateMonitor { get; }
+ private string ConnectionString { get; }
+ private string BackupConnectionString { get; }
+ private ShareConnectionStringFactory ConnectionStringFactory { get; }
private IShareScanner Scanner { get; }
- private IShareRepository Repository { get; }
private string LastOptionsHash { get; set; }
private IOptionsMonitor<Options> OptionsMonitor { get; }
- private List<Share> SharesList { get; set; } = new List<Share>();
+ private ConcurrentDictionary<string, (Host Host, IShareRepository Repository)> HostDictionary { get; set; } = new();
private IManagedState<ShareState> State { get; } = new ManagedState<ShareState>();
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1);
private StorageMode CacheStorageMode { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<ShareService>();
+ private (Host Host, IReadWriteShareRepository Repository) Local { get; set; }
+ private IEnumerable<IShareRepository> AllRepositories { get; set; }
+
+ /// <summary>
+ /// Adds a new, or updates an existing, share host.
+ /// </summary>
+ /// <param name="host">The host to add or update.</param>
+ public void AddOrUpdateHost(Host host)
+ {
+ HostDictionary.AddOrUpdate(
+ key: host.Name,
+ addValueFactory: (key) => (host, new SqliteShareRepository(ConnectionStringFactory.CreateFromFile(host.Name))),
+ updateValueFactory: (_, existing) => (host, existing.Repository));
+
+ AllRepositories = HostDictionary.Values
+ .Where(value => value.Host.State == HostState.Online)
+ .Select(value => value.Repository)
+ .Prepend(Local.Repository);
+ }
/// <summary>
/// Returns the entire contents of the share.
@@ -117,13 +159,13 @@ 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 Repository.ListDirectories(prefix))
+ foreach (var directory in AllRepositories.SelectMany(r => r.ListDirectories(prefix)))
{
var name = directory.NormalizePathForSoulseek();
directories.TryAdd(name, new Directory(name));
}
- var files = Repository.ListFiles(prefix, includeFullPath: true);
+ var files = AllRepositories.SelectMany(r => r.ListFiles(prefix, includeFullPath: true));
var groups = files
.GroupBy(file => Path.GetDirectoryName(file.Filename))
@@ -158,7 +200,7 @@ namespace slskd.Shares
{
var localPath = directory.LocalizePath();
- var files = Repository.ListFiles(localPath);
+ var files = AllRepositories.SelectMany(r => r.ListFiles(localPath));
return Task.FromResult(new Directory(directory, files));
}
@@ -174,7 +216,9 @@ namespace slskd.Shares
/// </exception>
public Task<FileInfo> ResolveFileAsync(string remoteFilename)
{
- var resolvedFilename = Repository.FindFilename(remoteFilename.LocalizePath());
+ var resolvedFilename = AllRepositories
+ .Select(r => r.FindFilename(remoteFilename.LocalizePath()))
+ .FirstOrDefault(r => !string.IsNullOrEmpty(r));
if (string.IsNullOrEmpty(resolvedFilename))
{
@@ -200,7 +244,7 @@ namespace slskd.Shares
/// <returns>The matching files.</returns>
public Task<IEnumerable<File>> SearchAsync(SearchQuery query)
{
- var results = Repository.Search(query);
+ var results = AllRepositories.SelectMany(r => r.Search(query));
return Task.FromResult(results.Select(r => new File(
r.Code,
@@ -215,9 +259,13 @@ namespace slskd.Shares
/// </summary>
/// <returns>The operation context.</returns>
/// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception>
- public Task ScanAsync()
+ public async Task ScanAsync()
{
- return Scanner.ScanAsync(Shares, OptionsMonitor.CurrentValue.Shares);
+ await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares);
+
+ Log.Debug("Backing up shared file cache database...");
+ Local.Repository.BackupTo(BackupConnectionString);
+ Log.Debug("Shared file cache database backup complete");
}
/// <summary>
@@ -229,8 +277,8 @@ namespace slskd.Shares
{
var prefix = share.RemotePath + Path.DirectorySeparatorChar;
- var dirs = Repository.CountDirectories(prefix);
- var files = Repository.CountFiles(prefix);
+ var dirs = AllRepositories.Select(r => r.CountDirectories(prefix)).Sum();
+ var files = AllRepositories.Select(r => r.CountFiles(prefix)).Sum();
return Task.FromResult((dirs, files));
}
@@ -263,11 +311,11 @@ namespace slskd.Shares
{
Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup...");
- if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup))
+ if (Local.Repository.TryValidate(BackupConnectionString))
{
Log.Information("Share cache backup validated. Attempting to restore...");
- Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup);
+ Local.Repository.RestoreFrom(connectionString: BackupConnectionString);
Log.Information("Share cache successfully restored from backup");
}
@@ -281,7 +329,7 @@ namespace slskd.Shares
{
Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate...");
- if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares))
+ if (Local.Repository.TryValidate(ConnectionString))
{
// no-op
}
@@ -289,11 +337,11 @@ namespace slskd.Shares
{
Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup...");
- if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup))
+ if (Local.Repository.TryValidate(BackupConnectionString))
{
Log.Information("Share cache backup validated. Attempting to restore...");
- Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup);
+ Local.Repository.RestoreFrom(connectionString: BackupConnectionString);
Log.Information("Share cache successfully restored from backup");
}
@@ -318,8 +366,8 @@ namespace slskd.Shares
Faulted = false,
Ready = true,
ScanProgress = 1,
- Directories = Repository.CountDirectories(),
- Files = Repository.CountFiles(),
+ Directories = Local.Repository.CountDirectories(),
+ Files = Local.Repository.CountFiles(),
});
}
catch (Exception ex)
@@ -359,9 +407,10 @@ namespace slskd.Shares
.OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent
.ToList();
- SharesList = shares;
+ Local = (Local.Host with { Shares = shares }, Local.Repository);
- State.SetValue(state => state with { ScanPending = true });
+ // todo: initialize agent hosts
+ // todo: don't destroy or overwrite existing hosts!
LastOptionsHash = optionsHash;
}