aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-11-23 18:38:02 -0600
committerJP Dillingham <jp@dillingham.me>2025-11-23 18:38:02 -0600
commit3e69af61e6ab42d79b9ff86adf7729e8abc70eed (patch)
tree41c799babd5509638bee59afe9bd995fc6e8c6c5 /src
parent119a3925da7fdf5f659bfa4c8e61e39a7148ba3e (diff)
parent318d1c16f80f6d48a408fb95b77c5a42402bf7df (diff)
downloadslskd-3e69af61e6ab42d79b9ff86adf7729e8abc70eed.tar.gz
Merge remote-tracking branch 'origin/master' into statistics
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs360
-rw-r--r--src/slskd/Common/RateLimiter.cs26
-rw-r--r--src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs43
-rw-r--r--src/slskd/Common/Validation/FileDoesNotExistAttribute.cs46
-rw-r--r--src/slskd/Common/Validation/FileExistsAttribute.cs3
-rw-r--r--src/slskd/Core/API/Controllers/OptionsController.cs5
-rw-r--r--src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs4
-rw-r--r--src/slskd/Core/Data/SqlitePragmaInterceptor.cs55
-rw-r--r--src/slskd/Core/Extensions.cs6
-rw-r--r--src/slskd/Core/Options.cs44
-rw-r--r--src/slskd/Events/EventsDbContext.cs1
-rw-r--r--src/slskd/Events/Types/Events.cs1
-rw-r--r--src/slskd/Files/FileService.cs19
-rw-r--r--src/slskd/Messaging/MessagingDbContext.cs1
-rw-r--r--src/slskd/Program.cs88
-rw-r--r--src/slskd/Search/API/Controllers/SearchesController.cs50
-rw-r--r--src/slskd/Search/SearchDbContext.cs1
-rw-r--r--src/slskd/Search/SearchService.cs4
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs4
-rw-r--r--src/slskd/Telemetry/API/TelemetryController.cs2
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs25
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs876
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs1
-rw-r--r--src/slskd/Transfers/Uploads/UploadQueue.cs32
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs717
-rw-r--r--src/slskd/slskd.csproj2
-rw-r--r--src/web/package-lock.json70
-rw-r--r--src/web/package.json2
-rw-r--r--src/web/src/components/System/System.css4
29 files changed, 1868 insertions, 624 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 98e3fcc7..1a18790f 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -188,8 +188,8 @@ namespace slskd
Client.LoggedIn += Client_LoggedIn;
Client.StateChanged += Client_StateChanged;
Client.DistributedNetworkStateChanged += Client_DistributedNetworkStateChanged;
- Client.DownloadDenied += (e, args) => Log.Information("Download of {Filename} from {Username} was denied: {Message}", args.Filename, args.Username, args.Message);
- Client.DownloadFailed += (e, args) => Log.Information("Download of {Filename} from {Username} failed", args.Filename, args.Username);
+ Client.DownloadDenied += (e, args) => Log.Error("Download of {Filename} from {Username} was denied by the remote user: {Message}", args.Filename, args.Username, args.Message);
+ Client.DownloadFailed += (e, args) => Log.Error("Download of {Filename} from {Username} reported as failed by the remote user", args.Filename, args.Username);
Client.ExcludedSearchPhrasesReceived += Client_ExcludedSearchPhrasesReceived;
@@ -220,6 +220,7 @@ namespace slskd
private OptionsAtStartup OptionsAtStartup { get; set; }
private IOptionsMonitor<Options> OptionsMonitor { get; set; }
private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1);
+ private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(20, 20);
private Options PreviousOptions { get; set; }
private IPushbulletService Pushbullet { get; }
private DateTime SharesRefreshStarted { get; set; }
@@ -375,18 +376,24 @@ namespace slskd
var connectionOptions = new ConnectionOptions(
readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read,
writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write,
- writeQueueSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue,
+ writeQueueSize: int.MaxValue, // no write queue for peer, server or transfer connections
connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect,
inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity,
proxyOptions: proxyOptions);
// os-specific keepalive is configured for long-lived connections for the server and distributed parent/children
- var serverOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, OptionsAtStartup.Soulseek.Connection));
- var distributedOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, OptionsAtStartup.Soulseek.Connection));
+ var serverOptions = connectionOptions.With(
+ inactivityTimeout: -1, // don't disconnect due to inactivity
+ configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, OptionsAtStartup.Soulseek.Connection));
+
+ var distributedOptions = connectionOptions.With(
+ writeQueueSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance
+ configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, OptionsAtStartup.Soulseek.Connection));
var transferOptions = connectionOptions.With(
readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer,
- writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer);
+ writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer,
+ inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Transfer);
var patch = new SoulseekClientOptionsPatch(
listenIPAddress: IPAddress.Parse(OptionsAtStartup.Soulseek.ListenIpAddress),
@@ -496,7 +503,7 @@ namespace slskd
return Task.CompletedTask;
}
- private void ConfigureSocketKeepAlive(Socket socket, Options.SoulseekOptions.ConnectionOptions options)
+ private void ConfigureSocketKeepaliveOptions(Socket socket, Options.SoulseekOptions.ConnectionOptions options)
{
/*
os-specific keepalive is configured for long-lived connections for the server and distributed parent/children
@@ -530,211 +537,226 @@ namespace slskd
// todo: consider moving this somewhere else; it's pretty long and complicated
private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename)
{
- if (Users.IsBlacklisted(username, endpoint.Address))
- {
- Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address);
- throw new DownloadEnqueueException("File not shared.");
- }
+ var stopwatch = new Stopwatch();
+ var decisionStopwatch = new Stopwatch();
- // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file
- // it helps, too, that this will tell us whether the file is even shared.
- (string Host, string Filename, long Size) resolved;
+ await EnqueueRequestRateLimiter.WaitAsync();
try
{
- resolved = await Shares.ResolveFileAsync(filename);
- }
- catch (NotFoundException)
- {
- throw new DownloadEnqueueException("File not shared.");
- }
+ stopwatch.Start();
- // get the user's group. this will be the name of the user's group, if they have been added to a
- // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted'
- var group = await Users.GetOrFetchGroupAsync(username);
+ if (Users.IsBlacklisted(username, endpoint.Address))
+ {
+ Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address);
+ throw new DownloadEnqueueException("File not shared.");
+ }
- // privileged users aren't subject to limits (for now)
- // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited"
- // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level
- // of control, but i'd need to figure out a lower bound
- if (string.Equals(group, PrivilegedGroup))
- {
- Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename);
- await Transfers.Uploads.EnqueueAsync(username, filename);
- return;
- }
+ // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file
+ // it helps, too, that this will tell us whether the file is even shared.
+ (string Host, string Filename, long Size) resolved;
- // we'll fall back to global limits for any limit that isn't set at the group level
- var global = Options.Global.Limits;
+ try
+ {
+ resolved = await Shares.ResolveFileAsync(filename);
+ }
+ catch (NotFoundException)
+ {
+ throw new DownloadEnqueueException("File not shared.");
+ }
- // resolve the limits for this user's group.
- Options.LimitsOptions limits;
+ // get the user's group. this will be the name of the user's group, if they have been added to a
+ // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted'
+ var group = await Users.GetOrFetchGroupAsync(username);
- if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions))
- {
- limits = userDefinedOptions.Limits;
- }
- else
- {
- limits = group switch
+ // privileged users aren't subject to limits (for now)
+ // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited"
+ // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level
+ // of control, but i'd need to figure out a lower bound
+ if (string.Equals(group, PrivilegedGroup))
{
- DefaultGroup => Options.Groups.Default.Limits,
- LeecherGroup => Options.Groups.Leechers.Limits,
- _ => Options.Groups.Default.Limits, // that's weird! we'll just go with defaults..
- };
- }
+ Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename);
+ await Transfers.Uploads.EnqueueAsync(username, filename);
+ return;
+ }
- bool IsNull(Options.LimitsOptions.Limits lim, Options.LimitsOptions.Limits global)
- => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null);
+ // we'll fall back to global limits for any limit that isn't set at the group level
+ var global = Options.Global.Limits;
- /*
- * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued.
- * the strategy here is to summarize all uploads:
- * 1) belonging to this user
- * 2) that were started within the time period
- * 3) that did not end due to an error (state includes errored, exception column is set)
- */
- (bool Files, bool Megabytes) OverLimits(
- (int Files, long Bytes) stats,
- Options.LimitsOptions.Limits options,
- Options.LimitsOptions.Limits defaults,
- long size)
- {
- var files = false;
- var megabytes = false;
- var byteLimitInMegabytes = options?.Megabytes ?? defaults?.Megabytes;
+ // resolve the limits for this user's group.
+ Options.LimitsOptions limits;
- if (byteLimitInMegabytes is not null && (stats.Bytes + size) > (byteLimitInMegabytes * 1000L * 1000L))
+ if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions))
{
- Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimitInMegabytes * 1000L * 1000L);
- megabytes = true;
+ limits = userDefinedOptions.Limits;
}
-
- var fileLimit = options?.Files ?? defaults?.Files;
-
- if (fileLimit is not null && (stats.Files + 1) > fileLimit)
+ else
{
- Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit);
- files = true;
+ limits = group switch
+ {
+ DefaultGroup => Options.Groups.Default.Limits,
+ LeecherGroup => Options.Groups.Leechers.Limits,
+ _ => Options.Groups.Default.Limits, // that's weird! we'll just go with defaults..
+ };
}
- return (files, megabytes);
- }
+ bool IsNull(Options.LimitsOptions.Limits lim, Options.LimitsOptions.Limits global)
+ => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null);
+
+ /*
+ * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued.
+ * the strategy here is to summarize all uploads:
+ * 1) belonging to this user
+ * 2) that were started within the time period
+ * 3) that did not end due to an error (state includes errored, exception column is set)
+ */
+ (bool Files, bool Megabytes) OverLimits(
+ (int Files, long Bytes) stats,
+ Options.LimitsOptions.Limits options,
+ Options.LimitsOptions.Limits defaults,
+ long size)
+ {
+ var files = false;
+ var megabytes = false;
+ var byteLimitInMegabytes = options?.Megabytes ?? defaults?.Megabytes;
- var sw = new Stopwatch();
- sw.Start();
+ if (byteLimitInMegabytes is not null && (stats.Bytes + size) > (byteLimitInMegabytes * 1000L * 1000L))
+ {
+ Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimitInMegabytes * 1000L * 1000L);
+ megabytes = true;
+ }
- // start with the queue, since that should contain the fewest files and should be the least expensive to check
- // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set
- // for terminal transfers.
- if (!IsNull(limits?.Queued, global?.Queued))
- {
- var queued = Transfers.Uploads.Summarize(
- expression: t => t.Username == username && t.EndedAt == null);
+ var fileLimit = options?.Files ?? defaults?.Files;
+
+ if (fileLimit is not null && (stats.Files + 1) > fileLimit)
+ {
+ Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit);
+ files = true;
+ }
- Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, sw.ElapsedMilliseconds);
+ return (files, megabytes);
+ }
- var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size);
+ decisionStopwatch.Start();
- if (over.Files || over.Megabytes)
+ // start with the queue, since that should contain the fewest files and should be the least expensive to check
+ // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set
+ // for terminal transfers.
+ if (!IsNull(limits?.Queued, global?.Queued))
{
- Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username);
+ var queued = Transfers.Uploads.Summarize(
+ expression: t => t.Username == username && t.EndedAt == null);
+
+ Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, decisionStopwatch.ElapsedMilliseconds);
+
+ var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size);
+
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username);
- // note: return exactly 'Too many files' or 'Too many megabytes' to ensure interop with other clients.
- // these messages are retryable, while anything else is not
- throw new DownloadEnqueueException($"Too many {(over.Megabytes ? "megabytes" : "files")}");
+ // note: return exactly 'Too many files' or 'Too many megabytes' to ensure interop with other clients.
+ // these messages are retryable, while anything else is not
+ throw new DownloadEnqueueException($"Too many {(over.Megabytes ? "megabytes" : "files")}");
+ }
}
- }
- // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum
- // transfers that 'count' for the weekly limit are uploads that:
- // * started within the last week
- // * which have or have not ended (assuming queued files will complete)
- // * that were not errored
- if (!IsNull(limits?.Weekly, global?.Weekly))
- {
- var erroredState = TransferStates.Completed | TransferStates.Errored;
- var cutoffDateTime = DateTime.UtcNow.AddDays(-7);
+ // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum
+ // transfers that 'count' for the weekly limit are uploads that:
+ // * started within the last week
+ // * which have or have not ended (assuming queued files will complete)
+ // * that were not errored
+ if (!IsNull(limits?.Weekly, global?.Weekly))
+ {
+ var erroredState = TransferStates.Completed | TransferStates.Errored;
+ var cutoffDateTime = DateTime.UtcNow.AddDays(-7);
- var failures = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && (t.State.HasFlag(erroredState) || t.Exception != null));
+ var failures = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && (t.State.HasFlag(erroredState) || t.Exception != null));
- Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, sw.ElapsedMilliseconds);
+ Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds);
- var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures;
+ var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures;
- if (failureLimit is not null && failures.Files >= failureLimit)
- {
- Log.Information("Rejected enqueue request for user {Username}: Weekly failure limit met or exceeded", username);
- throw new DownloadEnqueueException("Too many failed transfers this week");
- }
+ if (failureLimit is not null && failures.Files >= failureLimit)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Weekly failure limit met or exceeded", username);
+ throw new DownloadEnqueueException("Too many failed transfers this week");
+ }
- var weekly = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && !t.State.HasFlag(erroredState)
- && t.Exception == null);
+ var weekly = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && !t.State.HasFlag(erroredState)
+ && t.Exception == null);
- Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, sw.ElapsedMilliseconds);
+ Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, decisionStopwatch.ElapsedMilliseconds);
- var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size);
+ var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size);
- if (over.Files || over.Megabytes)
- {
- Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username);
- throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week");
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username);
+ throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week");
+ }
}
- }
- // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead
- // of the previous 7.
- if (!IsNull(limits?.Daily, global?.Daily))
- {
- var erroredState = TransferStates.Completed | TransferStates.Errored;
- var cutoffDateTime = DateTime.UtcNow.AddDays(-1);
+ // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead
+ // of the previous 7.
+ if (!IsNull(limits?.Daily, global?.Daily))
+ {
+ var erroredState = TransferStates.Completed | TransferStates.Errored;
+ var cutoffDateTime = DateTime.UtcNow.AddDays(-1);
- var failures = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && (t.State.HasFlag(erroredState) || t.Exception != null));
+ var failures = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && (t.State.HasFlag(erroredState) || t.Exception != null));
- Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, sw.ElapsedMilliseconds);
+ Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds);
- var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures;
+ var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures;
- if (failureLimit is not null && failures.Files >= failureLimit)
- {
- Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username);
- throw new DownloadEnqueueException("Too many failed transfers today");
- }
+ if (failureLimit is not null && failures.Files >= failureLimit)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username);
+ throw new DownloadEnqueueException("Too many failed transfers today");
+ }
- var daily = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && !t.State.HasFlag(erroredState)
- && t.Exception == null);
+ var daily = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && !t.State.HasFlag(erroredState)
+ && t.Exception == null);
- Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, sw.ElapsedMilliseconds);
+ Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, decisionStopwatch.ElapsedMilliseconds);
- var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size);
+ var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size);
- if (over.Files || over.Megabytes)
- {
- Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username);
- throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today");
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username);
+ throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today");
+ }
}
+
+ await Transfers.Uploads.EnqueueAsync(username, filename);
}
+ finally
+ {
+ decisionStopwatch.Stop();
+ stopwatch.Stop();
- sw.Stop();
- Log.Debug("Enqueue decision made in {Duration}ms", sw.ElapsedMilliseconds);
+ EnqueueRequestRateLimiter.Release();
- await Transfers.Uploads.EnqueueAsync(username, filename);
+ Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds);
+ }
}
/// <summary>
@@ -1382,12 +1404,18 @@ namespace slskd
inactivityTimeout: connection.Timeout.Inactivity,
proxyOptions: proxyPatch);
- serverPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, options: connection));
- distributedPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, options: connection));
+ serverPatch = connectionPatch.With(
+ inactivityTimeout: -1, // don't disconnect due to inactivity
+ configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, options: connection));
+
+ distributedPatch = connectionPatch.With(
+ writeQueueSize: connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance
+ configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, options: connection));
transferPatch = connectionPatch.With(
readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer,
- writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer);
+ writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer,
+ inactivityTimeout: connection.Timeout.Transfer);
}
var patch = new SoulseekClientOptionsPatch(
diff --git a/src/slskd/Common/RateLimiter.cs b/src/slskd/Common/RateLimiter.cs
index 8a7a63c6..b57c2f88 100644
--- a/src/slskd/Common/RateLimiter.cs
+++ b/src/slskd/Common/RateLimiter.cs
@@ -19,6 +19,7 @@ namespace slskd
{
using System;
using System.ComponentModel;
+ using System.Threading;
/// <summary>
/// Ensures a minimum interval between successive invocations of a delegate.
@@ -29,8 +30,11 @@ namespace slskd
/// Initializes a new instance of the <see cref="RateLimiter"/> class.
/// </summary>
/// <param name="interval">The minimum interval between invocations.</param>
+ /// <param name="concurrencyLimit">
+ /// Limit the number of concurrent executions of the specified action, in cases where the logic runs slower than the configured interval. Set this to null to remove the limit.
+ /// </param>
/// <param name="flushOnDispose">A value indicating whether pending action(s) should be executed during disposal.</param>
- public RateLimiter(int interval, bool flushOnDispose = false)
+ public RateLimiter(int interval, int? concurrencyLimit = 1, bool flushOnDispose = false)
{
Timer = new System.Timers.Timer(interval)
{
@@ -40,6 +44,11 @@ namespace slskd
Timer.Elapsed += Timer_Elapsed;
FlushOnDispose = flushOnDispose;
+
+ if (concurrencyLimit.HasValue)
+ {
+ ConcurrentExecutionPreventionSemaphore = new SemaphoreSlim(concurrencyLimit.Value, concurrencyLimit.Value);
+ }
}
private bool Disposed { get; set; }
@@ -47,6 +56,7 @@ namespace slskd
private bool Init { get; set; }
private Action Staged { get; set; }
private System.Timers.Timer Timer { get; set; }
+ private SemaphoreSlim ConcurrentExecutionPreventionSemaphore { get; } = null;
/// <summary>
/// Releases all resources used by the <see cref="Component"/>.
@@ -102,8 +112,18 @@ namespace slskd
private void Timer_Elapsed(object sender, EventArgs args)
{
- Staged?.Invoke();
- Staged = null;
+ if (ConcurrentExecutionPreventionSemaphore?.Wait(0) ?? true)
+ {
+ try
+ {
+ Staged?.Invoke();
+ Staged = null;
+ }
+ finally
+ {
+ ConcurrentExecutionPreventionSemaphore?.Release();
+ }
+ }
}
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs
new file mode 100644
index 00000000..fc70d9ea
--- /dev/null
+++ b/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs
@@ -0,0 +1,43 @@
+// <copyright file="AbsoluteFilePathAttribute.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+ using System.IO;
+
+ /// <summary>
+ /// Validates that the specified path is absolute.
+ /// </summary>
+ public class AbsoluteFilePathAttribute : ValidationAttribute
+ {
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value != null)
+ {
+ var filePath = value.ToString();
+
+ if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path.");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/FileDoesNotExistAttribute.cs b/src/slskd/Common/Validation/FileDoesNotExistAttribute.cs
new file mode 100644
index 00000000..69e01310
--- /dev/null
+++ b/src/slskd/Common/Validation/FileDoesNotExistAttribute.cs
@@ -0,0 +1,46 @@
+// <copyright file="FileDoesNotExistAttribute.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+ using System.IO;
+
+ /// <summary>
+ /// Validates that the file at the specified path does not exist.
+ /// </summary>
+ public class FileDoesNotExistAttribute : ValidationAttribute
+ {
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value != null)
+ {
+ var file = Path.GetFullPath(value?.ToString());
+
+ if (!string.IsNullOrEmpty(file))
+ {
+ if (File.Exists(file))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field specifies an existing file '{file}'.");
+ }
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs
index 762cd6b3..eae2b44a 100644
--- a/src/slskd/Common/Validation/FileExistsAttribute.cs
+++ b/src/slskd/Common/Validation/FileExistsAttribute.cs
@@ -53,7 +53,8 @@ namespace slskd.Validation
{
try
{
- File.Open(file, FileMode.Open, FileAccess.Value).Dispose();
+ using var fs = File.Open(file, FileMode.Open, FileAccess.Value);
+ fs.Close();
}
catch (IOException)
{
diff --git a/src/slskd/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs
index e39c5fe1..25e9095a 100644
--- a/src/slskd/Core/API/Controllers/OptionsController.cs
+++ b/src/slskd/Core/API/Controllers/OptionsController.cs
@@ -190,6 +190,11 @@ namespace slskd.Core.API
{
var options = yaml.FromYaml<Options>();
+ if (options is null)
+ {
+ return true;
+ }
+
if (!options.TryValidate(out var result))
{
error = result.GetResultView();
diff --git a/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs
index 9b3f14a8..8ae13734 100644
--- a/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs
+++ b/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs
@@ -41,8 +41,8 @@ public class Z07062025_TransferIndexesMigration : IMigration
var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString);
var txfers = idxes["Transfers"];
- var directionExists = txfers.Any(c => c.Name == "IDX_Transfers_Direction");
- var stateExists = txfers.Any(c => c.Name == "IDX_Transfers_State");
+ var directionExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Direction", StringComparison.OrdinalIgnoreCase));
+ var stateExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_State", StringComparison.OrdinalIgnoreCase));
if (directionExists && stateExists)
{
diff --git a/src/slskd/Core/Data/SqlitePragmaInterceptor.cs b/src/slskd/Core/Data/SqlitePragmaInterceptor.cs
new file mode 100644
index 00000000..b32982b1
--- /dev/null
+++ b/src/slskd/Core/Data/SqlitePragmaInterceptor.cs
@@ -0,0 +1,55 @@
+// <copyright file="SqlitePragmaInterceptor.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd
+{
+ using System.Data.Common;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using Microsoft.Data.Sqlite;
+ using Microsoft.EntityFrameworkCore.Diagnostics;
+
+ /// <summary>
+ /// Intercepts SQLite database connections to set PRAGMAs immediately after opening.
+ /// </summary>
+ public class SqliteConnectionOpenedInterceptor : DbConnectionInterceptor
+ {
+ public override void ConnectionOpened(DbConnection connection, ConnectionEndEventData eventData)
+ {
+ if (connection is SqliteConnection)
+ {
+ using var cmd = connection.CreateCommand();
+ cmd.CommandText = "PRAGMA synchronous=1;";
+ cmd.ExecuteNonQuery();
+ }
+
+ base.ConnectionOpened(connection, eventData);
+ }
+
+ public override async Task ConnectionOpenedAsync(DbConnection connection, ConnectionEndEventData eventData, CancellationToken cancellationToken = default)
+ {
+ if (connection is SqliteConnection)
+ {
+ using var cmd = connection.CreateCommand();
+ cmd.CommandText = "PRAGMA synchronous=1;";
+ await cmd.ExecuteNonQueryAsync(cancellationToken);
+ }
+
+ await base.ConnectionOpenedAsync(connection, eventData, cancellationToken);
+ }
+ }
+}
diff --git a/src/slskd/Core/Extensions.cs b/src/slskd/Core/Extensions.cs
index 65942180..db75cc9c 100644
--- a/src/slskd/Core/Extensions.cs
+++ b/src/slskd/Core/Extensions.cs
@@ -51,7 +51,7 @@ namespace slskd
/// <param name="connectTimeout">The connection timeout, in milliseconds, for client and peer TCP connections.</param>
/// <param name="inactivityTimeout">The inactivity timeout, in milliseconds, for peer TCP connections.</param>
/// <param name="proxyOptions">Optional SOCKS 5 proxy configuration options.</param>
- /// <param name="configureSocketAction">
+ /// <param name="configureSocket">
/// The delegate invoked during instantiation to configure the server Socket instance.
/// </param>
/// <returns>The new instance.</returns>
@@ -63,14 +63,14 @@ namespace slskd
int? connectTimeout = null,
int? inactivityTimeout = null,
ProxyOptions proxyOptions = null,
- Action<Socket> configureSocketAction = null) => new ConnectionOptions(
+ Action<Socket> configureSocket = null) => new ConnectionOptions(
readBufferSize: readBufferSize ?? o.ReadBufferSize,
writeBufferSize: writeBufferSize ?? o.WriteBufferSize,
writeQueueSize: writeQueueSize ?? o.WriteQueueSize,
connectTimeout: connectTimeout ?? o.ConnectTimeout,
inactivityTimeout: inactivityTimeout ?? o.InactivityTimeout,
proxyOptions: proxyOptions ?? o.ProxyOptions,
- configureSocket: configureSocketAction ?? o.ConfigureSocket);
+ configureSocket: configureSocket ?? o.ConfigureSocket);
/// <summary>
/// Creates a new instance of <see cref="UserStatisticsState"/> from this instance of <see cref="UserStatistics"/>.
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 4d4c1e68..ec94afcb 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -418,6 +418,15 @@ namespace slskd
public bool LogSQL { get; init; } = false;
/// <summary>
+ /// Gets a value indicating whether to log unobserved Exceptions.
+ /// </summary>
+ [Argument(default, "log-unobserved-exceptions")]
+ [EnvironmentVariable("LOG_UNOBSERVED_EXCEPTIONS")]
+ [Description("log unobserved exceptions (caution: verbose)")]
+ [RequiresRestart]
+ public bool LogUnobservedExceptions { get; init; } = false;
+
+ /// <summary>
/// Gets a value indicating whether the application should run in experimental mode.
/// </summary>
[Argument(default, "experimental")]
@@ -461,6 +470,22 @@ namespace slskd
[EnvironmentVariable("OPTIMISTIC_RELAY_FILE_INFO")]
[Description("use uploaded relay shares as source of truth for file existence and size")]
public bool OptimisticRelayFileInfo { get; init; } = false;
+
+ /// <summary>
+ /// Gets a value indicating whether SQLite cache sharing should be disabled (set to Private).
+ /// </summary>
+ [Argument(default, "no-sqlite-cache-sharing")]
+ [EnvironmentVariable("NO_SQLITE_CACHE_SHARING")]
+ [Description("disable SQLite cache sharing")]
+ public bool NoSqliteCacheSharing { get; init; } = false;
+
+ /// <summary>
+ /// Gets a value indicating whether SQLite pooling should be disabled.
+ /// </summary>
+ [Argument(default, "no-sqlite-pooling")]
+ [EnvironmentVariable("NO_SQLITE_POOLING")]
+ [Description("disable SQLite pooling")]
+ public bool NoSqlitePooling { get; init; } = false;
}
/// <summary>
@@ -1675,6 +1700,15 @@ namespace slskd
[Description("connection inactivity timeout, in milliseconds")]
[Range(1000, int.MaxValue)]
public int Inactivity { get; init; } = 15000;
+
+ /// <summary>
+ /// Gets the transfer connection timeout, in milliseconds.
+ /// </summary>
+ [Argument(default, "slsk-transfer-timeout")]
+ [EnvironmentVariable("SLSK_TRANSFER_TIMEOUT")]
+ [Description("transfer connection timeout, in milliseconds")]
+ [Range(30_000, int.MaxValue)]
+ public int Transfer { get; init; } = 60000;
}
/// <summary>
@@ -1807,6 +1841,16 @@ namespace slskd
public int Port { get; init; } = 5030;
/// <summary>
+ /// Gets the HTTP listen unix domain socket (UDS) path.
+ /// </summary>
+ [Argument(default, "http-socket")]
+ [EnvironmentVariable("HTTP_SOCKET")]
+ [Description("HTTP listen unix domain socket (UDS) path for web UI")]
+ [AbsoluteFilePath]
+ [RequiresRestart]
+ public string Socket { get; init; }
+
+ /// <summary>
/// Gets HTTPS options.
/// </summary>
[Validate]
diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs
index a86f5d1c..8b45a803 100644
--- a/src/slskd/Events/EventsDbContext.cs
+++ b/src/slskd/Events/EventsDbContext.cs
@@ -25,7 +25,6 @@ public class EventsDbContext : DbContext
public EventsDbContext(DbContextOptions<EventsDbContext> options)
: base(options)
{
- Database.EnsureCreated();
}
public DbSet<EventRecord> Events { get; set; }
diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs
index 6e99b800..577e41e3 100644
--- a/src/slskd/Events/Types/Events.cs
+++ b/src/slskd/Events/Types/Events.cs
@@ -28,6 +28,7 @@ public enum EventType
DownloadFileComplete = 2,
DownloadDirectoryComplete = 3,
UploadFileComplete = 4,
+
// UploadDirectoryComplete = 5,
PrivateMessageReceived = 6,
RoomMessageReceived = 7,
diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs
index a07bd051..e4adc7e7 100644
--- a/src/slskd/Files/FileService.cs
+++ b/src/slskd/Files/FileService.cs
@@ -379,6 +379,7 @@ namespace slskd.Files
/// </remarks>
/// <param name="sourceFilename">The fully qualified filename of the file to move.</param>
/// <param name="destinationDirectory">The fully qualified directory to which to move the source file.</param>
+ /// <param name="unixFileMode">An optional Unix file mode to apply to the destination file.</param>
/// <param name="overwrite">An optional value indicating whether the destination file should be overwritten if it already exists.</param>
/// <param name="deleteSourceDirectoryIfEmptyAfterMove">
/// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move.
@@ -387,7 +388,7 @@ namespace slskd.Files
/// <exception cref="ArgumentNullException">Thrown if either of the specified file or directories are null or contain only whitespace.</exception>
/// <exception cref="FileNotFoundException">Thrown if the specified <paramref name="sourceFilename"/> does not exist.</exception>
/// <exception cref="IOException">Thrown if the file can't be moved, or the <paramref name="deleteSourceDirectoryIfEmptyAfterMove"/> option is set and the operation fails.</exception>
- public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false)
+ public virtual string MoveFile(string sourceFilename, string destinationDirectory, UnixFileMode? unixFileMode = null, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename));
ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory));
@@ -425,6 +426,22 @@ namespace slskd.Files
Log.Debug("Successfully moved {Source} to {Destination}", sourceFilename, destinationFilename);
+ // attempting to use UnixCreateMode on Windows raises an Exception
+ // we *MUST* check the OS and skip this on Windows
+ if (!OperatingSystem.IsWindows())
+ {
+ var appOption = OptionsMonitor.CurrentValue.Permissions.File.Mode;
+ var mode = unixFileMode ?? appOption?.ToUnixFileMode();
+
+ // if options haven't been passed in and none have been set in app config, omit this
+ // so that the application's umask will be applied, saving users the hassle of setting it twice.
+ if (mode.HasValue)
+ {
+ File.SetUnixFileMode(destinationFilename, mode.Value);
+ Log.Debug("Successfully set Unix file mode to {Mode}", mode);
+ }
+ }
+
// if the parent directory is empty after the move, delete it
if (deleteSourceDirectoryIfEmptyAfterMove && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any())
{
diff --git a/src/slskd/Messaging/MessagingDbContext.cs b/src/slskd/Messaging/MessagingDbContext.cs
index 5acb94ae..c6352c6e 100644
--- a/src/slskd/Messaging/MessagingDbContext.cs
+++ b/src/slskd/Messaging/MessagingDbContext.cs
@@ -25,7 +25,6 @@ namespace slskd.Messaging
public MessagingDbContext(DbContextOptions<MessagingDbContext> options)
: base(options)
{
- Database.EnsureCreated();
}
public DbSet<Conversation> Conversations { get; set; }
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index bafab7f5..edfe06bc 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -23,6 +23,8 @@ namespace slskd
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
+ using System.Diagnostics;
+
using System.IO;
using System.Linq;
using System.Net;
@@ -237,6 +239,7 @@ namespace slskd
private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup();
private static ILogger Log { get; set; } = new ConsoleWriteLineLogger();
private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName));
+ private static IDisposable DotNetRuntimeStats { get; set; }
[Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")]
private static bool GenerateCertificate { get; set; }
@@ -475,6 +478,12 @@ namespace slskd
Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/");
options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port);
+ if (OptionsAtStartup.Web.Socket != null)
+ {
+ Log.Information($"Listening for HTTP requests on unix domain socket (UDS) {OptionsAtStartup.Web.Socket}");
+ options.ListenUnixSocket(OptionsAtStartup.Web.Socket);
+ }
+
if (!OptionsAtStartup.Web.Https.Disabled)
{
Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/");
@@ -585,7 +594,9 @@ namespace slskd
new SoulseekClient(options: new SoulseekClientOptions(
maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots,
maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots,
- minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>())));
+ minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(),
+ maximumConcurrentSearches: 2,
+ raiseEventsAsynchronously: true)));
// add the core application service to DI as well as a hosted service so that other services can
// access instance methods
@@ -600,9 +611,12 @@ namespace slskd
var connectionStringDictionary = new ConnectionStringDictionary(Database.List
.Select(database =>
{
+ var caching = OptionsAtStartup.Flags.NoSqliteCacheSharing ? "Private" : "Shared";
+ var pooling = OptionsAtStartup.Flags.NoSqlitePooling ? "False" : "True"; // don't invert and ToString this it is confusing
+
var connStr = OptionsAtStartup.Flags.Volatile
- ? $"Data Source=file:{database}?mode=memory;Cache=shared;Pooling=True;"
- : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache=shared;Pooling=True;";
+ ? $"Data Source=file:{database}?mode=memory;Cache={caching};Pooling={pooling};"
+ : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache={caching};Pooling={pooling}";
return new KeyValuePair<Database, ConnectionString>(database, connStr);
})
@@ -698,8 +712,10 @@ namespace slskd
.AllowCredentials()
.WithExposedHeaders("X-URL-Base", "X-Total-Count")));
+ // note: don't dispose this (or let it be disposed) or some of the stats, like those related
+ // to the thread pool won't work
+ DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Default().StartCollecting();
services.AddSystemMetrics();
- using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting();
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys")));
@@ -1128,6 +1144,30 @@ namespace slskd
}
}))
.CreateLogger();
+
+ if (OptionsAtStartup.Flags.LogUnobservedExceptions)
+ {
+ // log Exceptions raised on fired-and-forgotten tasks, which adds very little value but might help debug someday
+ TaskScheduler.UnobservedTaskException += (sender, e) =>
+ {
+ Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message);
+ e.SetObserved();
+ };
+ }
+
+ AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
+ {
+ var exception = e.ExceptionObject as Exception;
+
+ if (e.IsTerminating)
+ {
+ Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", e.IsTerminating);
+ }
+ else
+ {
+ Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception.Message);
+ }
+ };
}
private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile, bool reloadOnChange)
@@ -1174,6 +1214,7 @@ namespace slskd
services.AddDbContextFactory<T>(options =>
{
options.UseSqlite(connectionString);
+ options.AddInterceptors(new SqliteConnectionOpenedInterceptor());
if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL)
{
@@ -1181,11 +1222,50 @@ namespace slskd
}
});
+ /*
+ instantiate the DbContext and make sure it is created
+ */
using var ctx = services
.BuildServiceProvider()
.GetRequiredService<IDbContextFactory<T>>()
.CreateDbContext();
+ Log.Debug("Ensuring {Contex} is created", typeof(T).Name);
+ ctx.Database.EnsureCreated();
+
+ /*
+ set (and validate) our desired PRAGMAs
+
+ synchronous mode is also set upon every connection via SqliteConnectionOpenedInterceptor.
+ */
+ ctx.Database.OpenConnection();
+ var conn = ctx.Database.GetDbConnection();
+
+ Log.Debug("Setting PRAGMAs for {Contex}", typeof(T).Name);
+ using var initCommand = conn.CreateCommand();
+ initCommand.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=1; PRAGMA optimize;";
+ initCommand.ExecuteNonQuery();
+
+ using var journalCmd = conn.CreateCommand();
+ journalCmd.CommandText = "PRAGMA journal_mode;";
+ var journalMode = journalCmd.ExecuteScalar()?.ToString();
+
+ if (!journalMode.Equals("WAL", StringComparison.OrdinalIgnoreCase))
+ {
+ Log.Warning("Failed to set database {Type} journal_mode PRAGMA to WAL; performance may be reduced", typeof(T).Name);
+ }
+
+ using var syncCmd = conn.CreateCommand();
+ syncCmd.CommandText = "PRAGMA synchronous;";
+ var sync = syncCmd.ExecuteScalar()?.ToString();
+
+ if (!sync.Equals("1", StringComparison.OrdinalIgnoreCase))
+ {
+ Log.Warning("Failed to set database {Type} synchronous PRAGMA to 1; performance may be reduced", typeof(T).Name);
+ }
+
+ Log.Debug("PRAGMAs for {Context}: journal_mode={JournalMode}, synchronous={Synchronous}", typeof(T).Name, journalMode, sync);
+
return services;
}
catch (Exception ex)
diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs
index 1d00b482..c51d537e 100644
--- a/src/slskd/Search/API/Controllers/SearchesController.cs
+++ b/src/slskd/Search/API/Controllers/SearchesController.cs
@@ -20,6 +20,7 @@ using Microsoft.Extensions.Options;
namespace slskd.Search.API
{
using System;
+ using System.Threading;
using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
@@ -49,6 +50,7 @@ namespace slskd.Search.API
OptionsSnapshot = optionsSnapshot;
}
+ private static SemaphoreSlim SearchRequestLimiter { get; } = new SemaphoreSlim(1, 1);
private ISearchService Searches { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
private ILogger Log { get; set; } = Serilog.Log.ForContext<SearchesController>();
@@ -75,29 +77,41 @@ namespace slskd.Search.API
return BadRequest("SearchText may not be null or empty");
}
- var id = request.Id ?? Guid.NewGuid();
-
- Search search;
-
- try
+ if (!SearchRequestLimiter.Wait(0))
{
- search = await Searches.StartAsync(id, SearchQuery.FromText(request.SearchText), SearchScope.Network, request.ToSearchOptions());
- return Ok(search);
+ return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes");
}
- catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException)
- {
- Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message);
- return BadRequest(ex.Message);
- }
- catch (InvalidOperationException ex)
+
+ try
{
- Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message);
- return Conflict(ex.Message);
+ var id = request.Id ?? Guid.NewGuid();
+
+ Search search;
+
+ try
+ {
+ search = await Searches.StartAsync(id, SearchQuery.FromText(request.SearchText), SearchScope.Network, request.ToSearchOptions());
+ return Ok(search);
+ }
+ catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException)
+ {
+ Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message);
+ return BadRequest(ex.Message);
+ }
+ catch (InvalidOperationException ex)
+ {
+ Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message);
+ return Conflict(ex.Message);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
}
- catch (Exception ex)
+ finally
{
- Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message);
- return StatusCode(500, ex.Message);
+ SearchRequestLimiter.Release();
}
}
diff --git a/src/slskd/Search/SearchDbContext.cs b/src/slskd/Search/SearchDbContext.cs
index bc6ee147..1d710e42 100644
--- a/src/slskd/Search/SearchDbContext.cs
+++ b/src/slskd/Search/SearchDbContext.cs
@@ -25,7 +25,6 @@ namespace slskd.Search
public SearchDbContext(DbContextOptions<SearchDbContext> options)
: base(options)
{
- Database.EnsureCreated();
}
public DbSet<Search> Searches { get; set; }
diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs
index 920f7e54..37630f98 100644
--- a/src/slskd/Search/SearchService.cs
+++ b/src/slskd/Search/SearchService.cs
@@ -321,7 +321,7 @@ namespace slskd.Search
// a search that was actually cancelled by the user will meet the criteria below.
if (ex is OperationCanceledException && cancellationTokenSource.Token.IsCancellationRequested)
{
- Log.Information("Search for '{Query}' was cancelled");
+ Log.Information("Search for '{Query}' was cancelled", query);
search.State = SearchStates.Completed | SearchStates.Cancelled;
}
else
@@ -350,7 +350,7 @@ namespace slskd.Search
await SearchHub.BroadcastUpdateAsync(search with { Responses = [] });
Log.Debug("Search for '{Query}' finalized (id: {Id}): {Search}", query, id, search with { Responses = [] });
- Log.Information("Search for '{Query}' completed with {Responses} responses", search.ResponseCount);
+ Log.Information("Search for '{Query}' completed with {Responses} responses", query, search.ResponseCount);
}
catch (Exception ex)
{
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index f457adba..711bb21e 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -157,7 +157,9 @@ namespace slskd.Shares
{
using var conn = GetConnection();
- conn.ExecuteNonQuery("PRAGMA journal_mode=WAL");
+ // warning: with synchronous=0, an operating system crash can leave the database corrupted.
+ // if this occurs we should generate a new one, so this is _probably_ ok
+ conn.ExecuteNonQuery("PRAGMA journal_mode=WAL; PRAGMA synchronous=0;");
if (discardExisting)
{
diff --git a/src/slskd/Telemetry/API/TelemetryController.cs b/src/slskd/Telemetry/API/TelemetryController.cs
index 6098f432..2ea69443 100644
--- a/src/slskd/Telemetry/API/TelemetryController.cs
+++ b/src/slskd/Telemetry/API/TelemetryController.cs
@@ -58,7 +58,7 @@ public class TelemetryController : ControllerBase
/// * node_filesystem_avail_bytes = how much space is left on the system
/// * node_network = info about network adapters on the system
/// Other
- /// * process_start_time_seconds = unix timestamp of start time
+ /// * process_start_time_seconds = unix timestamp of start time.
/// </summary>
private List<Regex> KpiRegexes { get; } = new List<Regex>
{
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index fdbca1dc..6be11b2d 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -23,10 +23,12 @@ namespace slskd.Transfers.API
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
+ using System.Threading;
using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+ using Serilog;
/// <summary>
/// Transfers.
@@ -51,8 +53,10 @@ namespace slskd.Transfers.API
OptionsSnapshot = optionsSnapshot;
}
+ private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2);
private ITransferService Transfers { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
+ private ILogger Log { get; set; } = Serilog.Log.ForContext<TransfersController>();
/// <summary>
/// Cancels the specified download.
@@ -204,22 +208,37 @@ namespace slskd.Transfers.API
[ProducesResponseType(201)]
[ProducesResponseType(typeof(string), 403)]
[ProducesResponseType(typeof(string), 500)]
- public async Task<IActionResult> EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable<QueueDownloadRequest> requests)
+#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
+#pragma warning disable SA1611 // Element parameters should be documented
+ public async Task<IActionResult> EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable<QueueDownloadRequest> requests, CancellationToken cancellationToken = default)
+#pragma warning restore SA1611 // Element parameters should be documented
+#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
{
if (Program.IsRelayAgent)
{
return Forbid();
}
+ if (!DownloadRequestLimiter.Wait(0))
+ {
+ return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes");
+ }
+
try
{
- await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)));
- return StatusCode(201);
+ var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken);
+
+ return StatusCode(201, new { Enqueued = enqueued, Failed = failed });
}
catch (Exception ex)
{
+ Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message);
return StatusCode(500, ex.Message);
}
+ finally
+ {
+ DownloadRequestLimiter.Release();
+ }
}
/// <summary>
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index 92191ab7..65b5977f 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -25,6 +25,7 @@ namespace slskd.Transfers.Downloads
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
+ using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
@@ -55,11 +56,12 @@ namespace slskd.Transfers.Downloads
/// </remarks>
/// <param name="username">The username of remote user.</param>
/// <param name="files">The list of files to enqueue.</param>
+ /// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files);
+ Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default);
/// <summary>
/// Finds a single download matching the specified <paramref name="expression"/>.
@@ -133,8 +135,28 @@ namespace slskd.Transfers.Downloads
FTP = ftpClient;
Relay = relayService;
EventBus = eventBus;
+
+ Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync());
}
+ /// <summary>
+ /// These tokens give users the ability to cancel transfers via the UI (or API).
+ ///
+ /// The lifecycle is:
+ ///
+ /// 1. in EnqueueAsync(), just before transfer records are added to the database, these CTS are created and
+ /// added to the dictionary
+ /// 2. in EnqueueAsync(), if there was an error or any condition which caused the transfer to not proceed was met,
+ /// the CTS is removed from the dictionary and disposed
+ /// 3. in DownloadAsync(), in the finally block after all post-download logic has been executed, the CTS
+ /// is removed and disposed.
+ ///
+ /// The CTS should be in the dictionary the entire time the transfer is "in flight", from the first moment it
+ /// comes into being (via database insert) until the eventual download process has completed or failed.
+ ///
+ /// Every cancellable operation in this flow needs to use this CTS token either directly or by linking it with another,
+ /// or we risk transfers getting stuck with no way for users to get rid of them.
+ /// </summary>
private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>();
private ISoulseekClient Client { get; }
private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
@@ -146,6 +168,19 @@ namespace slskd.Transfers.Downloads
private EventBus EventBus { get; }
/// <summary>
+ /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they
+ /// don't already exist, and a timer asynchronously cleans the dictionary up.
+ /// </summary>
+ private ConcurrentDictionary<string, SemaphoreSlim> EnqueueSemaphores { get; } = [];
+
+ /// <summary>
+ /// Synchronizes the cleanup process; after gaining exclusive access over the dictionary, checks each entry
+ /// to see if the containing semaphore can be obtained immediately. If so, it's not in use and is therefore
+ /// removed from the dictionary and discarded.
+ /// </summary>
+ private SemaphoreSlim EnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(initialCount: 1, maxCount: 1);
+
+ /// <summary>
/// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
/// </summary>
/// <remarks>This should generally not be called; use EnqueueAsync() instead.</remarks>
@@ -155,11 +190,11 @@ namespace slskd.Transfers.Downloads
using var context = ContextFactory.CreateDbContext();
var existing = context.Transfers
- .Where(t => t.Direction == TransferDirection.Download)
- .Where(t => t.Username == transfer.Username)
- .Where(t => t.Filename == transfer.Filename)
- .Where(t => !t.Removed)
- .FirstOrDefault();
+ .Where(t => t.Direction == TransferDirection.Download)
+ .Where(t => t.Username == transfer.Username)
+ .Where(t => t.Filename == transfer.Filename)
+ .Where(t => !t.Removed)
+ .FirstOrDefault();
if (existing != default)
{
@@ -174,276 +209,356 @@ namespace slskd.Transfers.Downloads
/// <summary>
/// Enqueues the requested list of <paramref name="files"/>.
/// </summary>
- /// <remarks>
- /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be
- /// thrown after all files are dispositioned if any throws.
- /// </remarks>
/// <param name="username">The username of the remote user.</param>
/// <param name="files">The list of files to enqueue.</param>
+ /// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- public Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files)
+ public async Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(username))
{
throw new ArgumentException("Username is required", nameof(username));
}
- if (!files.Any())
+ var fileList = files.ToList();
+
+ if (fileList.Count == 0)
+ {
+ throw new ArgumentException("At least one file is required", nameof(files));
+ }
+
+ if (fileList.Count != fileList.Distinct().Count())
{
- throw new ArgumentException("At least one file is require", nameof(files));
+ throw new ArgumentException("Two or more files in request are duplicated", nameof(files));
}
- return EnqueueAsyncInternal(username, files);
+ IPEndPoint endpoint;
+
+ Log.Information("Requested enqueue of {Count} files from user {Username}", fileList.Count, username);
- async Task EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files)
+ // get the user's ip and port. this will throw if they are offline.
+ try
{
- try
+ endpoint = await Client.GetUserEndPointAsync(username, cancellationToken);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", fileList.Count, username, ex.Message);
+ throw;
+ }
+
+ // prime the cache for this user, to 1) make sure we can connect, and 2) avoid needing to race for it in the loop
+ try
+ {
+ Log.Debug("Priming message connection to {Username}", username);
+ await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message);
+ throw;
+ }
+
+ List<Transfer> enqueued = [];
+ List<string> failed = [];
+
+ SemaphoreSlim userSemaphore;
+ Task userSemaphoreWaitTask;
+
+ Log.Debug("Awaiting enqueue semaphore sync root");
+ await EnqueueSemaphoreSyncRoot.WaitAsync(cancellationToken);
+
+ try
+ {
+ Log.Debug("Acquired enqueue semaphore sync root");
+ userSemaphore = EnqueueSemaphores.GetOrAdd(username, (username) => new SemaphoreSlim(initialCount: 1, maxCount: 1));
+ userSemaphoreWaitTask = userSemaphore.WaitAsync(cancellationToken);
+ }
+ finally
+ {
+ EnqueueSemaphoreSyncRoot.Release();
+ Log.Debug("Released enqueue semaphore sync root");
+ }
+
+ Log.Debug("Awaiting enqueue semaphore for user {Username}", username);
+ await userSemaphoreWaitTask;
+
+ try
+ {
+ Log.Debug("Acquired enqueue semaphore for user {Username}", username);
+
+ using var context = ContextFactory.CreateDbContext();
+
+ /*
+ get all past downloads from this user. this list will remain stable throughout this process because
+ we have exclusive access for this user. we'll be adding new records, but we've already deduplicated
+ them so we don't have to worry about duplicate records being created in the critical section
+ */
+ var existingRecords = context.Transfers
+ .Where(t => t.Direction == TransferDirection.Download)
+ .Where(t => t.Username == username)
+ .AsNoTracking()
+ .ToList();
+
+ var existingInProgressRecords = existingRecords
+ .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
+ .ToDictionary(t => t.Filename, t => t);
+
+ /*
+ determine how many concurrent enqueue requests we want to send to the remote client.
+
+ sending a ton of them can bog the client down and fail transfers due to resource contention on both sides,
+ but both clients should be able to handle momentary 'bursts'.
+
+ if the request contains 30 files or fewer, send all of the requests at the same time. the average number
+ of tracks in a single album is 15, so this is 2x as many as most enqueue requests will need.
+
+ if that number is more than 30, send only 5 at a time; transfers will be starting as we are still
+ enqueueing files, and this raises the risk of errors considerably.
+ */
+ var concurrentEnqueueRequests = 5;
+
+ if (fileList.Count <= 30)
{
- Log.Information("Downloading {Count} files from user {Username}", files.Count(), username);
+ concurrentEnqueueRequests = fileList.Count;
+ }
+
+ var maxTimeToWaitForEnqueueRequestAck = TimeSpan.FromMinutes(3);
+ var enqueueSemaphore = new SemaphoreSlim(initialCount: concurrentEnqueueRequests, maxCount: concurrentEnqueueRequests);
- Log.Debug("Priming connection for user {Username}", username);
- await Client.ConnectToUserAsync(username, invalidateCache: false);
- Log.Debug("Connection for user '{Username}' primed", username);
+ /*
+ iterate over each of the files in the request. each file must be dispositioned as one of the following:
- var thrownExceptions = new List<Exception>();
+ 1. enqueued: passed duplicate checks and successfully kicked off a Task to enqueue the download
+ 2. failed: download is already in progress, or something went wrong kicking off the Task
- foreach (var file in files)
+ if we fail to enqueue a file, we must call TryFail() to ensure that if a record was inserted, it is
+ given a final disposition that will keep it from getting 'stuck'
+ */
+ foreach (var file in fileList)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ Guid transferId = Guid.NewGuid();
+
+ try
{
- Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username);
+ Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username);
+
+ /*
+ if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already
+ an existing transfer record covering this file, and we're already enqueued. nothing more to do!
+
+ check the tracked download dictionary in Soulseek.NET to see if it knows about this already
+ it shouldn't, if the slskd database doesn't. but things could get desynced
+ */
+ existingInProgressRecords.TryGetValue(file.Filename, out var existingInProgressRecord);
- var id = Guid.NewGuid();
+ if (existingInProgressRecord is not null || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename))
+ {
+ Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id);
+ failed.Add(file.Filename);
+ continue;
+ }
+ /*
+ add the transfer record to the database in the Queued | Locally state, and set the 'Removed'
+ property of any existing transfer to 'true', allowing the new record to supersede any old record(s)
+ on the UI
+
+ we have to persist these changes to the database at this time so the record shows up on the UI,
+ otherwise the transfers only show up as they are enqueued.
+ */
var transfer = new Transfer()
{
- Id = id,
+ Id = transferId,
Username = username,
Direction = TransferDirection.Download,
- Filename = file.Filename,
+ Filename = file.Filename, // important! use the remote filename
Size = file.Size,
- StartOffset = 0,
+ StartOffset = 0, // todo: maybe implement resumeable downloads?
RequestedAt = DateTime.UtcNow,
+ State = TransferStates.Queued | TransferStates.Locally,
};
- // persist the transfer to the database so we have a record that it was attempted
- AddOrSupersede(transfer);
+ context.Add(transfer);
+
+ Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id);
- var cts = new CancellationTokenSource();
- CancellationTokens.TryAdd(id, cts);
+ foreach (var record in existingRecords.Where(t => t.Filename == file.Filename && !t.Removed))
+ {
+ record.Removed = true;
+ context.Update(record);
+ Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id);
+ }
+
+ /*
+ create a TaskCompletionSource that we can await for one of the following:
+
+ 1. the transfer enters the Queued | Remotely state
+ 2. the transfer enters a state containing Completed
+ 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled
+ 4. the 'max wait time' CancellationTokenSource is cancelled
+
+ add this to the dictionary before inserting the record, so we are guaranteed to have it
+ in the right place once the transfer hits the UI
+ */
+ var enqueuedTcs = new TaskCompletionSource<Transfer>();
- var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
+ // satisfies condition #3; CancellationTokenSource set cancelled by the user (via API call)
+ var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ CancellationTokens.TryAdd(transfer.Id, cts);
+ cts.Token.Register(() => enqueuedTcs.TrySetCanceled());
- // this task does the actual work of downloading the file. if the transfer is successfully queued
- // remotely, the waitUntilEnqueue completion source is set, which yields execution to below so we can
- // return and let the caller know.
- var downloadTask = Task.Run(async () =>
+ /*
+ DANGER ZONE! this record is in the database now; we're on the hook for making sure it ends up
+ with a State that includes the Completed flag, else it remain "stuck" on the UI
+ */
+ context.SaveChanges();
+
+ Log.Debug("Scheduling Task for enqueue of {Filename} from {Username}", file.Filename, username);
+
+ var downloadEnqueueTask = Task.Run(async () =>
{
- using var rateLimiter = new RateLimiter(250, flushOnDispose: true);
- var syncRoot = new SemaphoreSlim(1, 1);
+ Log.Debug("Awaiting download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);
+ await enqueueSemaphore.WaitAsync(cts.Token);
- void SynchronizedUpdate(Transfer transfer, bool cancellable = true)
+ try
{
- syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None);
+ Log.Debug("Acquired download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);
- try
+ List<string> transitions = [];
+ TransferStates state = TransferStates.None;
+
+ // satisfies condition #4; remote user doesn't respond after a really long time
+ using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForEnqueueRequestAck);
+ timeoutCts.Token.Register(() =>
{
- Update(transfer);
- }
- finally
+ Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit of {Duration} seconds. State transition history: {History}", transfer.Filename, username, maxTimeToWaitForEnqueueRequestAck.TotalSeconds, string.Join(", ", transitions));
+ enqueuedTcs.TrySetException(new TimeoutException($"Download failed to enqueue remotely after hard time limit of {maxTimeToWaitForEnqueueRequestAck.TotalSeconds} secs"));
+ });
+
+ // satisfies conditions #1 and #2
+ void stateChanged(Transfer transfer)
{
- syncRoot.Release();
- }
- }
+ state = transfer.State;
+ transitions.Add(transfer.State.ToString());
- try
- {
- var topts = new TransferOptions(
- disposeOutputStreamOnCompletion: true,
- stateChanged: (args) =>
+ if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely))
{
- Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, args.PreviousState, args.Transfer.State);
+ // satisfies condition #1; transfer is now remotely queued
+ enqueuedTcs.TrySetResult(transfer);
+ }
- if (Application.IsShuttingDown)
+ // satisfies condition #2; transfer advanced to a terminal state before being enqueued remotely (probably failed)
+ if (transfer.State.HasFlag(TransferStates.Completed))
+ {
+ if (transfer.State.HasFlag(TransferStates.Succeeded))
{
- Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", file.Filename, username);
- return;
+ enqueuedTcs.TrySetResult(transfer);
}
-
- transfer = transfer.WithSoulseekTransfer(args.Transfer);
-
- if ((args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) || args.Transfer.State == TransferStates.Initializing)
+ else
{
- transfer.EnqueuedAt = DateTime.UtcNow;
- waitUntilEnqueue.TrySetResult(true);
+ enqueuedTcs.TrySetException(new TransferException(transfer.Exception));
}
-
- SynchronizedUpdate(transfer);
- },
- progressUpdated: (args) => rateLimiter.Invoke(() =>
- {
- transfer = transfer.WithSoulseekTransfer(args.Transfer);
-
- // todo: broadcast to signalr hub
- SynchronizedUpdate(transfer);
- }));
-
- var completedTransfer = await Client.DownloadAsync(
- username: username,
- remoteFilename: file.Filename,
- outputStreamFactory: () => Task.FromResult(
- Files.CreateFile(
- filename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete),
- options: new CreateFileOptions
- {
- Access = System.IO.FileAccess.Write,
- Mode = System.IO.FileMode.Create, // overwrites file if it exists
- Share = System.IO.FileShare.None, // exclusive access for the duration of the download
- UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode)
- ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode()
- : null,
- })),
- size: file.Size,
- startOffset: 0,
- token: null,
- cancellationToken: cts.Token,
- options: topts);
-
- // explicitly dispose the rate limiter to prevent updates from it
- // beyond this point, which may overwrite the final state
- rateLimiter.Dispose();
-
- transfer = transfer.WithSoulseekTransfer(completedTransfer);
-
- // todo: broadcast to signalr hub
- SynchronizedUpdate(transfer, cancellable: false);
-
- var destinationDirectory = System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads));
-
- var finalFilename = Files.MoveFile(
- sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete),
- destinationDirectory: destinationDirectory,
- overwrite: false,
- deleteSourceDirectoryIfEmptyAfterMove: true);
-
- Log.Debug("Moved file to {Destination}", finalFilename);
-
- // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary,
- // and the file has been moved from the incomplete directory to the downloads directory
- if (OptionsMonitor.CurrentValue.Relay.Enabled)
- {
- _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename);
+ }
}
- EventBus.Raise(new DownloadFileCompleteEvent
- {
- Timestamp = transfer.EndedAt.Value,
- LocalFilename = finalFilename,
- RemoteFilename = transfer.Filename,
- Transfer = transfer,
- });
-
- // try to figure out if this file is the last of a directory, and if so, raise the associated
- // event. this can be tricky because we want to be sure that this is the last file in this specific
- // directory, excluding any pending downloads in a subdirectory.
- var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator();
- var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator);
- var pendingDownloadsInDirectory = Client.Downloads
- .Where(t => t.Username == transfer.Username)
- .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName);
+ Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username);
- if (!pendingDownloadsInDirectory.Any())
+ var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken: cts.Token)).ContinueWith(task =>
{
- EventBus.Raise(new DownloadDirectoryCompleteEvent
+ if (task.IsCompletedSuccessfully)
{
- Timestamp = transfer.EndedAt.Value,
- Username = transfer.Username,
- LocalDirectoryName = destinationDirectory,
- RemoteDirectoryName = remoteDirectoryName,
- });
- }
+ Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username);
+ return;
+ }
- if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled)
- {
- _ = FTP.UploadAsync(finalFilename);
- }
- }
- catch (OperationCanceledException ex)
- {
- transfer.EndedAt = DateTime.UtcNow;
- transfer.Exception = ex.Message;
- transfer.State = TransferStates.Completed | TransferStates.Cancelled;
+ Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException?.Message ?? task.Exception.Message);
- // todo: broadcast to signalr hub
- SynchronizedUpdate(transfer, cancellable: false);
+ if (!TryFail(transferId, exception: task.Exception))
+ {
+ Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message);
+ }
+ }, cancellationToken: CancellationToken.None); // end downloadTask.Run();
- throw;
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", file.Filename, username, ex.Message);
+ Log.Debug("Download Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadTask.Status);
- transfer.EndedAt = DateTime.UtcNow;
- transfer.State = TransferStates.Completed | TransferStates.Errored;
+ Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely);
- // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
- // exceptions in a database. when we encounter one of these, drop the first segment.
- transfer.Exception = ex.Message.Contains(':') ? ex.Message.Substring(ex.Message.IndexOf(':') + 1).Trim() : ex.Message;
+ /*
+ wait for one of the four conditions to be true:
- // todo: broadcast to signalr hub
- SynchronizedUpdate(transfer, cancellable: false);
+ 1. the transfer enters the Queued | Remotely state
+ 2. the transfer enters a state containing Completed
+ 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled
+ 4. the 'max wait time' CancellationTokenSource is cancelled
+ */
+ await enqueuedTcs.Task;
- throw;
+ Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", transfer.Filename, transfer.Username, state);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Download of {File} from {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
+ if (!TryFail(transferId, exception: ex))
+ {
+ Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message);
+ }
}
finally
{
- CancellationTokens.TryRemove(id, out _);
+ enqueueSemaphore.Release();
}
- });
-
- // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or
- // the downloadTask throws due to an error prior to successfully queueing.
- var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask);
-
- // if the download task completed first it is a very good indication that it threw an exception or was
- // otherwise not successful. try to figure out why and update everything to reflect the failure, but
- // continue processing the batch
- if (task == downloadTask)
+ }, cancellationToken: cts.Token).ContinueWith(task =>
{
- Exception ex = downloadTask.Exception;
+ if (task.IsCompletedSuccessfully)
+ {
+ Log.Information("Task for enqueue of {Filename} from {Username} completed successfully", file.Filename, username);
+ return;
+ }
+
+ Log.Error(task.Exception, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException?.Message ?? task.Exception.Message);
- // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate?
- if (ex is AggregateException aggEx)
+ if (!TryFail(transferId, exception: task.Exception))
{
- var rejected = aggEx.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty<Exception>();
- if (rejected.Any())
- {
- ex = rejected.First();
- }
+ Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message);
}
+ }, cancellationToken: CancellationToken.None); // end downloadEnqueueTask.Run();
- Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
- thrownExceptions.Add(ex);
- }
- else
+ Log.Debug("Download enqueue Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadEnqueueTask.Status);
+ Log.Information("Successfully locally enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transfer.Id);
+ enqueued.Add(transfer);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
+ TryFail(transferId, exception: ex);
+ failed.Add(file.Filename);
+
+ if (CancellationTokens.TryRemove(transferId, out var cts))
{
- Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username);
+ cts.Dispose();
}
- }
- if (thrownExceptions.Any())
- {
- throw new AggregateException(thrownExceptions);
+ continue;
}
+ } // end foreach()
- Log.Information("Successfully enqueued {Count} file(s) from user {Username}", files.Count(), username);
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message);
- throw;
- }
+ Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username);
+ return (enqueued, failed);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", fileList.Count, username, ex.Message);
+ throw;
+ }
+ finally
+ {
+ userSemaphore.Release();
+ Log.Debug("Released enqueue semaphore for user {Username}", username);
}
}
@@ -621,12 +736,78 @@ namespace slskd.Transfers.Downloads
/// <returns>A value indicating whether the download was successfully cancelled.</returns>
public bool TryCancel(Guid id)
{
+ // if the cancellation token is still in the dictionary, calling Cancel() on it _should_
+ // cause the transfer operation to fail with an OperationCancelled exception and set the state
+ // of the transfer to Cancelled. _should_!
if (CancellationTokens.TryRemove(id, out var cts))
{
cts.Cancel();
return true;
}
+ /*
+ if the cancellation token couldn't be found in the dictionary, either:
+
+ 1. the transfer completed already
+ 2. something went wrong and the record is 'stuck'
+
+ see if we can find the record, and if it's *NOT* completed, cancel it. otherwise,
+ leave it alone.
+ */
+ var t = Find(t => t.Id == id);
+
+ if (t is not null && !t.State.HasFlag(TransferStates.Completed))
+ {
+ t.EndedAt = DateTime.UtcNow;
+ t.State = TransferStates.Completed | TransferStates.Cancelled;
+ t.Exception = new OperationCanceledException().Message;
+ Update(t);
+ return true;
+ }
+
+ // this transfer id didn't have a cancellation token registered, and we couldn't find it in the dictionary
+ return false;
+ }
+
+ /// <summary>
+ /// Fails the download matching the specified <paramref name="id"/> with the specified <paramref name="exception"/>,
+ /// and sets the final state accordingly.
+ /// </summary>
+ /// <remarks>
+ /// This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change
+ /// the EndedAt or Exception properties if they have already been set. If the transfer State already includes
+ /// the terminal Completed flag, it is unchanged.
+ /// </remarks>
+ /// <param name="id">The unique identifier for the download.</param>
+ /// <param name="exception">The exception that caused the failure.</param>
+ /// <returns>A value indicating whether the download was successfully failed.</returns>
+ public bool TryFail(Guid id, Exception exception)
+ {
+ var t = Find(t => t.Id == id);
+
+ if (t is not null)
+ {
+ t.EndedAt ??= DateTime.UtcNow;
+
+ // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
+ // exceptions in a database. when we encounter one of these, drop the first segment.
+ var m = exception.Message;
+ t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;
+
+ if (!t.State.HasFlag(TransferStates.Completed))
+ {
+ t.State = TransferStates.Completed | exception switch
+ {
+ OperationCanceledException => TransferStates.Cancelled,
+ TimeoutException => TransferStates.TimedOut,
+ _ => TransferStates.Errored,
+ };
+ }
+
+ Update(t);
+ return true;
+ }
+
return false;
}
@@ -641,5 +822,296 @@ namespace slskd.Transfers.Downloads
context.Update(transfer);
context.SaveChanges();
}
+
+ /// <summary>
+ /// Downloads the specified enqueued <paramref name="transfer"/> from the remote user.
+ /// </summary>
+ /// <param name="transfer">The Transfer to download.</param>
+ /// <param name="stateChanged">An optional delegate to invoke the transfer state changes.</param>
+ /// <param name="cancellationToken">The token to monitor for cancellation.</param>
+ /// <returns>The operation context.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception>
+ /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception>
+ /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception>
+ /// <exception cref="DuplicateTransferException">Thrown if a download matching the username and filename is already tracked by Soulseek.NET.</exception>
+ private async Task<Transfer> DownloadAsync(Transfer transfer, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default)
+ {
+ if (transfer is null)
+ {
+ throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required");
+ }
+
+ // grab the latest from the database; this may have been sitting behind a semaphore or something
+ transfer = Find(t => t.Id == transfer.Id)
+ ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found");
+
+ if (transfer.State != (TransferStates.Queued | TransferStates.Locally))
+ {
+ throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}");
+ }
+
+ if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename))
+ {
+ throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered");
+ }
+
+ // there _should_ be a cancellation token for this transfer in the dictionary; if so link it with the one we are given
+ // (which is probably the same one, harmless if so) to make sure we don't get any wires crossed
+ CancellationTokens.TryGetValue(transfer.Id, out var cancellationTokenSource);
+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancellationTokenSource?.Token ?? CancellationToken.None);
+ cancellationToken = cts.Token;
+
+ var updateSyncRoot = new SemaphoreSlim(1, 1);
+
+ try
+ {
+ using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true);
+
+ var topts = new TransferOptions(
+ stateChanged: (args) =>
+ {
+ try
+ {
+ Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.Transfer.State);
+
+ // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions;
+ // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup
+ if (Application.IsShuttingDown)
+ {
+ Log.Debug("Download update of {Filename} from {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username);
+ return;
+ }
+
+ transfer = transfer.WithSoulseekTransfer(args.Transfer);
+
+ // we don't know when the download is actually enqueued (remotely) until it switches into that state
+ // when it is enqueued locally is irrelevant, due to internal throttling etc
+ if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely))
+ {
+ transfer.EnqueuedAt ??= DateTime.UtcNow;
+ }
+
+ // todo: broadcast
+ SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken);
+ }
+ finally
+ {
+ stateChanged?.Invoke(transfer);
+ }
+ },
+ progressUpdated: (args) => rateLimiter.Invoke(() =>
+ {
+ // don't do anything unless the `transfer` within the outer scope is in the
+ // InProgress state; this will help prevent out-of-band updates that are sometimes
+ // being made after the transfer is completed, causing them to appear 'stuck'
+ if (transfer.State == TransferStates.InProgress)
+ {
+ // don't wait for the semaphore; if a previous progress update is still hanging, don't make
+ // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems
+ // but the alternative is to continue to stack slow writes on top of one another
+ if (updateSyncRoot.Wait(millisecondsTimeout: 0, cancellationToken: cancellationToken))
+ {
+ try
+ {
+ // update only the properties that we expect to change between progress updates
+ // this helps prevent this update from 'stepping' on other updates
+ transfer.BytesTransferred = args.Transfer.BytesTransferred;
+ transfer.AverageSpeed = args.Transfer.AverageSpeed;
+
+ using var context = ContextFactory.CreateDbContext();
+
+ context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter
+ .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred)
+ .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed));
+ }
+ finally
+ {
+ updateSyncRoot.Release();
+ }
+ }
+ else
+ {
+ Log.Debug("Skipped progress update of {Filename} from {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size);
+ }
+ }
+ }),
+ disposeOutputStreamOnCompletion: true);
+
+ System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode)
+ ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode()
+ : null;
+
+ Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username);
+
+ var completedTransfer = await Client.DownloadAsync(
+ username: transfer.Username,
+ remoteFilename: transfer.Filename,
+ outputStreamFactory: () => Task.FromResult(
+ Files.CreateFile(
+ filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete),
+ options: new CreateFileOptions
+ {
+ Access = System.IO.FileAccess.Write,
+ Mode = System.IO.FileMode.Create, // overwrites file if it exists
+ Share = System.IO.FileShare.None, // exclusive access for the duration of the download
+ UnixCreateMode = unixFileMode,
+ })),
+ size: transfer.Size,
+ startOffset: 0,
+ token: null,
+ cancellationToken: cancellationToken,
+ options: topts);
+
+ Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username);
+
+ // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we
+ // flush any pending update, _probably_ pushing the state of the transfer back to InProgress
+ rateLimiter.Dispose();
+
+ // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state
+ // over the top of the transfer record, then persist it
+ transfer = transfer.WithSoulseekTransfer(completedTransfer);
+
+ // todo: broadcast to signalr hub
+ SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);
+
+ Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete);
+
+ // move the file from incomplete to complete
+ var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads));
+
+ var finalFilename = Files.MoveFile(
+ sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete),
+ destinationDirectory: destinationDirectory,
+ unixFileMode: unixFileMode,
+ overwrite: false,
+ deleteSourceDirectoryIfEmptyAfterMove: true);
+
+ Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename);
+
+ if (OptionsMonitor.CurrentValue.Relay.Enabled)
+ {
+ _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename);
+ }
+
+ try
+ {
+ // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary,
+ // and the file has been moved from the incomplete directory to the downloads directory
+ Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username);
+
+ EventBus.Raise(new DownloadFileCompleteEvent
+ {
+ Timestamp = transfer.EndedAt.Value,
+ LocalFilename = finalFilename,
+ RemoteFilename = transfer.Filename,
+ Transfer = transfer,
+ });
+
+ // try to figure out if this file is the last of a directory, and if so, raise the associated
+ // event. this can be tricky because we want to be sure that this is the last file in this specific
+ // directory, excluding any pending downloads in a subdirectory.
+ var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator();
+ var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator);
+ var pendingDownloadsInDirectory = Client.Downloads
+ .Where(t => t.Username == transfer.Username)
+ .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName);
+
+ if (!pendingDownloadsInDirectory.Any())
+ {
+ EventBus.Raise(new DownloadDirectoryCompleteEvent
+ {
+ Timestamp = transfer.EndedAt.Value,
+ Username = transfer.Username,
+ LocalDirectoryName = destinationDirectory,
+ RemoteDirectoryName = remoteDirectoryName,
+ });
+ }
+
+ if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled)
+ {
+ _ = FTP.UploadAsync(finalFilename);
+ }
+
+ Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username);
+ }
+ catch (Exception ex)
+ {
+ // log, but don't throw. the file ended up in the download folder and is complete; if we throw it looks like it didn't complete
+ // todo: add a visual indicator/new state for Transfers that indicate this state. or move all of this logic out and handle it via events
+ Log.Error(ex, "Failed to run post-download processes for {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message);
+ }
+
+ Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username);
+
+ return transfer;
+ }
+ catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
+ {
+ Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
+
+ TryFail(transfer.Id, exception: ex);
+
+ // todo: broadcast
+ SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);
+
+ throw;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
+
+ TryFail(transfer.Id, exception: ex);
+
+ // todo: broadcast
+ SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);
+
+ throw;
+ }
+ finally
+ {
+ if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource))
+ {
+ storedCancellationTokenSource?.Dispose();
+ }
+ }
+ }
+
+ private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default)
+ {
+ semaphore.Wait(cancellationToken);
+
+ try
+ {
+ Update(transfer);
+ }
+ finally
+ {
+ semaphore.Release();
+ }
+ }
+
+ private async Task CleanupEnqueueSemaphoresAsync()
+ {
+ if (await EnqueueSemaphoreSyncRoot.WaitAsync(0).ConfigureAwait(false))
+ {
+ try
+ {
+ foreach (var kvp in EnqueueSemaphores)
+ {
+ if (await kvp.Value.WaitAsync(0).ConfigureAwait(false))
+ {
+ EnqueueSemaphores.TryRemove(kvp.Key, out var removed);
+ removed.Dispose();
+ Log.Debug("Cleaned up enqueue semaphore for {Key}", kvp.Key);
+ }
+ }
+ }
+ finally
+ {
+ EnqueueSemaphoreSyncRoot.Release();
+ }
+ }
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs
index ea138bcd..eac4935b 100644
--- a/src/slskd/Transfers/TransfersDbContext.cs
+++ b/src/slskd/Transfers/TransfersDbContext.cs
@@ -26,7 +26,6 @@ namespace slskd.Transfers
public TransfersDbContext(DbContextOptions<TransfersDbContext> options)
: base(options)
{
- Database.EnsureCreated();
}
public DbSet<Transfer> Transfers { get; set; }
diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs
index c24f66cf..c20e2312 100644
--- a/src/slskd/Transfers/Uploads/UploadQueue.cs
+++ b/src/slskd/Transfers/Uploads/UploadQueue.cs
@@ -50,6 +50,15 @@ namespace slskd.Transfers
void Complete(string username, string filename);
/// <summary>
+ /// Gracefully attempts to signal the completion of an upload, returning false if a problem is encountered
+ /// (such as the upload not being tracked currently).
+ /// </summary>
+ /// <param name="username">The username of the remote user.</param>
+ /// <param name="filename">The completed filename.</param>
+ /// <returns>A value indicating whether a problem was encountered.</returns>
+ bool TryComplete(string username, string filename);
+
+ /// <summary>
/// Enqueues an upload.
/// </summary>
/// <param name="username">The username of the remote user.</param>
@@ -152,8 +161,31 @@ namespace slskd.Transfers
}
/// <summary>
+ /// Gracefully attempts to signal the completion of an upload, returning false if a problem is encountered
+ /// (such as the upload not being tracked currently).
+ /// </summary>
+ /// <param name="username">The username of the remote user.</param>
+ /// <param name="filename">The completed filename.</param>
+ /// <returns>A value indicating whether a problem was encountered.</returns>
+ public bool TryComplete(string username, string filename)
+ {
+ try
+ {
+ Complete(username, filename);
+ return true;
+ }
+ catch (SlskdException)
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
/// Signals the completion of an upload.
/// </summary>
+ /// <remarks>
+ /// Will not throw on repeated attempts.
+ /// </remarks>
/// <param name="username">The username of the remote user.</param>
/// <param name="filename">The completed filename.</param>
public void Complete(string username, string filename)
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index 485b138b..1aa97603 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -64,7 +64,19 @@ namespace slskd.Transfers.Uploads
/// <param name="username">The username of the requesting user.</param>
/// <param name="filename">The local filename of the requested file.</param>
/// <returns>The operation context.</returns>
- Task EnqueueAsync(string username, string filename);
+ Task<Transfer> EnqueueAsync(string username, string filename);
+
+ /// <summary>
+ /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user.
+ /// </summary>
+ /// <param name="transfer">The Transfer to upload.</param>
+ /// <returns>The operation context.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception>
+ /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception>
+ /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception>
+ /// <exception cref="DuplicateTransferException">Thrown if an upload matching the username and filename is already tracked by Soulseek.NET.</exception>
+ /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception>
+ Task<Transfer> UploadAsync(Transfer transfer);
/// <summary>
/// Finds a single upload matching the specified <paramref name="expression"/>.
@@ -168,6 +180,7 @@ namespace slskd.Transfers.Uploads
private IShareService Shares { get; set; }
private IUserService Users { get; set; }
private EventBus EventBus { get; }
+ private ConcurrentDictionary<string, bool> Locks { get; } = new();
/// <summary>
/// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
@@ -179,11 +192,11 @@ namespace slskd.Transfers.Uploads
using var context = ContextFactory.CreateDbContext();
var existing = context.Transfers
- .Where(t => t.Direction == TransferDirection.Upload)
- .Where(t => t.Username == transfer.Username)
- .Where(t => t.Filename == transfer.Filename)
- .Where(t => !t.Removed)
- .FirstOrDefault();
+ .Where(t => t.Direction == TransferDirection.Upload)
+ .Where(t => t.Username == transfer.Username)
+ .Where(t => t.Filename == transfer.Filename)
+ .Where(t => !t.Removed)
+ .FirstOrDefault();
if (existing != default)
{
@@ -196,257 +209,507 @@ namespace slskd.Transfers.Uploads
}
/// <summary>
- /// Enqueues the requested file.
+ /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user.
/// </summary>
- /// <param name="username">The username of the requesting user.</param>
- /// <param name="filename">The local filename of the requested file.</param>
+ /// <param name="transfer">The Transfer to upload.</param>
/// <returns>The operation context.</returns>
- public async Task EnqueueAsync(string username, string filename)
+ /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception>
+ /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception>
+ /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception>
+ /// <exception cref="DuplicateTransferException">Thrown if an upload matching the username and filename is already tracked by Soulseek.NET.</exception>
+ /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception>
+ public async Task<Transfer> UploadAsync(Transfer transfer)
{
+ var cts = new CancellationTokenSource();
+ var syncRoot = new SemaphoreSlim(1, 1);
+
string host = default;
string localFilename = default;
- long resolvedFileLength = default;
long localFileLength = default;
- Log.Information("[{Context}] {Username} requested {Filename}", "UPLOAD REQUESTED", username, filename);
+ var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}";
+
+ if (!Locks.TryAdd(lockName, true))
+ {
+ Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName);
+ return null;
+ }
+
+ /*
+ from this point forward, any exit from this method MUST result in an update to the Transfer record
+ in the database that sets EndedAt and ensures that the State property includes the Completed flag
+ failure to do so means records will get "stuck" in the database/on the UI
+
+ additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot
+ */
try
{
- (host, localFilename, resolvedFileLength) = await Shares.ResolveFileAsync(filename);
+ Log.Debug("Acquired lock {LockName}", lockName);
- Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename);
+ /*
+ fetch an updated copy of the transfer record from the database; now that we are locked, we *should*
+ have exclusive access to this record
- if (host == Program.LocalHostName)
- {
- // if it's local, do a quick check to see if it exists to spare the caller from queueing up if the transfer is
- // doomed to fail. for remote files, take a leap of faith.
- var info = Files.ResolveFileInfo(localFilename);
+ we're not using DbContext and tracked changes here because we don't want to hold a connection
+ open for the duration of the upload
+ */
+ transfer = Find(t => t.Id == transfer.Id)
+ ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found");
- if (!info.Exists)
- {
- Shares.RequestScan();
- throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed.");
- }
+ if (transfer.State != (TransferStates.Queued | TransferStates.Locally))
+ {
+ throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}");
+ }
- localFileLength = info.Length;
+ /*
+ Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic;
+ check that list to see if there's already an instance of this upload in it, just in case we've gotten
+ out of sync somehow
+ */
+ if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename))
+ {
+ throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered");
}
- else
+
+ // users with uploads must be watched so that we can keep informed of their online status, privileges, and
+ // statistics. this is so that we can accurately determine their effective group.
+ try
{
- if (OptionsMonitor.CurrentValue.Flags.OptimisticRelayFileInfo)
+ if (!Users.IsWatched(transfer.Username))
{
- localFileLength = resolvedFileLength;
+ await Users.WatchAsync(transfer.Username);
}
- else
+ }
+ catch (Exception ex)
+ {
+ Log.Warning(ex, "Failed to watch user {Username}", transfer.Username);
+ }
+
+ Log.Information("Initializing upload of {Filename} to {Username}", transfer.Filename, transfer.Username);
+
+ // locate the file on disk. we checked this once already when enqueueing, but it may have moved since
+ // can throw NotFoundException
+ (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: transfer.Filename);
+
+ using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true);
+
+ var topts = new TransferOptions(
+ stateChanged: (args) =>
{
- var (exists, length) = await Relay.GetFileInfoAsync(agentName: host, filename);
+ Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, transfer.Username, args.PreviousState, args.Transfer.State);
- if (!exists || length <= 0)
+ // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions;
+ // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup
+ if (Application.IsShuttingDown)
{
- // todo: force a remote scan
- throw new NotFoundException($"The file '{localFilename}' could not be located on Agent {host}. A share scan should be performed.");
+ Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username);
+ return;
}
- localFileLength = length;
- }
+ transfer = transfer.WithSoulseekTransfer(args.Transfer);
+
+ // todo: broadcast
+ SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token);
+ },
+ progressUpdated: (args) => rateLimiter.Invoke(() =>
+ {
+ // don't do anything unless the `transfer` within the outer scope is in the
+ // InProgress state; this will help prevent out-of-band updates that are sometimes
+ // being made after the transfer is completed, causing them to appear 'stuck'
+ if (transfer.State == TransferStates.InProgress)
+ {
+ // don't wait for the semaphore; if a previous progress update is still hanging, don't make
+ // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems
+ // but the alternative is to continue to stack slow writes on top of one another
+ if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token))
+ {
+ try
+ {
+ // update only the properties that we expect to change between progress updates
+ // this helps prevent this update from 'stepping' on other updates
+ transfer.BytesTransferred = args.Transfer.BytesTransferred;
+ transfer.AverageSpeed = args.Transfer.AverageSpeed;
+
+ using var context = ContextFactory.CreateDbContext();
+
+ context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter
+ .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred)
+ .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed));
+ }
+ finally
+ {
+ syncRoot.Release();
+ }
+ }
+ else
+ {
+ Log.Debug("Skipped progress update of {Filename} to {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size);
+ }
+ }
+ }),
+ seekInputStreamAutomatically: false,
+ disposeInputStreamOnCompletion: true, // note: don't set this to false!
+ governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct),
+ reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act),
+ slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename),
+ slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename));
+
+ // register the cancellation token
+ CancellationTokens.TryAdd(transfer.Id, cts);
+
+ // add the transfer to the UploadQueue so that it can become eligible for selection
+ Queue.Enqueue(transfer.Username, transfer.Filename);
+ transfer.EnqueuedAt = DateTime.UtcNow;
+ SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token);
+
+ Soulseek.Transfer completedTransfer;
+
+ if (host == Program.LocalHostName)
+ {
+ completedTransfer = await Client.UploadAsync(
+ username: transfer.Username,
+ remoteFilename: transfer.Filename,
+ size: localFileLength,
+ inputStreamFactory: (startOffset) =>
+ {
+#pragma warning disable S2930 // "IDisposables" should be disposed
+ // disposeInputStreamOnCompletion takes care of this
+ var stream = new FileStream(localFilename, FileMode.Open, FileAccess.Read);
+#pragma warning restore S2930 // "IDisposables" should be disposed
+
+ stream.Seek(startOffset, SeekOrigin.Begin);
+ return Task.FromResult((Stream)stream);
+ },
+ options: topts,
+ cancellationToken: cts.Token);
}
+ else
+ {
+ completedTransfer = await Client.UploadAsync(
+ username: transfer.Username,
+ remoteFilename: transfer.Filename,
+ size: localFileLength,
+ inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: transfer.Filename, startOffset, id: transfer.Id),
+ options: topts,
+ cancellationToken: cts.Token);
+
+ Relay.TryCloseFileStream(host, id: transfer.Id);
+ }
+
+ // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we
+ // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress
+ rateLimiter.Dispose();
+
+ // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state
+ // over the top of the transfer record, then persist it
+ transfer = transfer.WithSoulseekTransfer(completedTransfer);
+
+ // todo: broadcast
+ SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
+
+ EventBus.Raise(new UploadFileCompleteEvent
+ {
+ Timestamp = transfer.EndedAt.Value,
+ LocalFilename = localFilename,
+ RemoteFilename = transfer.Filename,
+ Transfer = transfer,
+ });
+
+ return transfer;
}
catch (NotFoundException)
{
- Log.Information("[{Context}] {Filename} for {Username}: file not found", "UPLOAD REJECTED", username, filename);
- throw new DownloadEnqueueException($"File not shared.");
+ transfer.EndedAt = DateTime.Now;
+ transfer.Exception = "File could not be found";
+ transfer.State = TransferStates.Completed | TransferStates.Aborted;
+
+ SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
+
+ throw;
}
+ catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
+ {
+ transfer.EndedAt = DateTime.UtcNow;
+ transfer.Exception = ex.Message;
+ transfer.State = TransferStates.Completed;
+
+ transfer.State |= ex switch
+ {
+ OperationCanceledException => TransferStates.Cancelled,
+ TimeoutException => TransferStates.TimedOut,
+ _ => TransferStates.Errored,
+ };
- Log.Information("Resolved {Remote} to physical file {Physical} on host '{Host}'", filename, localFilename, host);
+ // todo: broadcast
+ SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
- if (localFileLength != resolvedFileLength)
+ throw;
+ }
+ catch (Exception ex)
{
- // todo: should we fail the transfer? the file changed on disk since the last scan. i guess not? since the caller doesn't provide a size
- Shares.RequestScan();
- Log.Warning("Resolved size for {Remote} of {Resolved} doesn't match actual size {Actual}", filename, resolvedFileLength, localFileLength);
+ Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
+
+ transfer.EndedAt = DateTime.UtcNow;
+ transfer.Exception = ex.Message;
+ transfer.State = TransferStates.Completed | TransferStates.Errored;
+
+ // todo: broadcast
+ SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
+
+ throw;
}
+ finally
+ {
+ if (host != Program.LocalHostName)
+ {
+ try
+ {
+ Relay.TryCloseFileStream(host, id: transfer.Id);
+ }
+ catch
+ {
+ // noop
+ }
+ }
- // find existing records for this username and file that haven't been removed from the UI
- var existingRecords = List(t => t.Username == username && t.Filename == localFilename, includeRemoved: false);
+ try
+ {
+ Locks.TryRemove(lockName, out _);
+ Log.Debug("Released lock {LockName}", lockName);
+
+ CancellationTokens.TryRemove(transfer.Id, out _);
+
+ // if for some reason this logic exits without the slotReleased delegate and Complete() being invoked,
+ // the file will get stuck in the queue and prevent any further uploads to the user. be extra cautious
+ // and ensure it gets removed
+ Queue.TryComplete(username: transfer.Username, filename: transfer.Filename);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message);
+ throw;
+ }
+ }
+ }
- // check whether any of these records is in a non-complete state and bail out if so
- if (existingRecords.Any(t => !t.State.HasFlag(TransferStates.Completed)))
+ /// <summary>
+ /// Enqueues the requested file.
+ /// </summary>
+ /// <param name="username">The username of the requesting user.</param>
+ /// <param name="filename">The local filename of the requested file.</param>
+ /// <returns>The operation context.</returns>
+ public async Task<Transfer> EnqueueAsync(string username, string filename)
+ {
+ if (string.IsNullOrEmpty(username))
{
- Log.Information("Upload {Filename} to {Username} is already queued or in progress", localFilename, username);
- return;
+ throw new ArgumentNullException(nameof(username), "Username is required");
}
- var id = Guid.NewGuid();
+ if (string.IsNullOrEmpty(filename))
+ {
+ throw new ArgumentNullException(nameof(filename), "Filename is required");
+ }
+
+ var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}";
- var transfer = new Transfer()
+ if (!Locks.TryAdd(lockName, true))
{
- Id = id,
- Username = username,
- Direction = TransferDirection.Upload,
- Filename = localFilename,
- Size = localFileLength,
- StartOffset = 0, // potentially updated later during handshaking
- RequestedAt = DateTime.UtcNow,
- };
-
- // persist the transfer to the database so we have a record that it was attempted
- AddOrSupersede(transfer);
-
- // create a new cancellation token source so that we can cancel the upload from the UI.
- var cts = new CancellationTokenSource();
- CancellationTokens.TryAdd(id, cts);
+ Log.Debug("Ignoring concurrent upload enqueue attempt; lock {LockName} already held", lockName);
+ return null;
+ }
+
+ Guid id = Guid.NewGuid();
- // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and
- // uploads would be handled separately.
- _ = Task.Run(async () =>
+ try
{
- using var rateLimiter = new RateLimiter(250, flushOnDispose: true);
- var syncRoot = new SemaphoreSlim(1, 1);
+ Log.Debug("Acquired lock {LockName}", lockName);
- void SynchronizedUpdate(Transfer transfer, bool cancellable = true)
+ Log.Information("Upload of {Filename} to {Username} requested", filename, username);
+
+ using var context = ContextFactory.CreateDbContext();
+
+ /*
+ first, get all past uploads to this user for this filename
+ */
+ var existingRecords = context.Transfers
+ .Where(t => t.Direction == TransferDirection.Upload)
+ .Where(t => t.Username == username)
+ .Where(t => t.Filename == filename)
+ .AsNoTracking()
+ .ToList();
+
+ var existingInProgressRecords = existingRecords
+ .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
+ .ToList();
+
+ /*
+ if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already
+ an existing transfer record covering this file, and we're already enqueued. nothing more to do!
+ */
+ if (existingInProgressRecords.Count != 0)
{
- syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None);
+ Log.Information("Upload of {Filename} to {Username} is already queued or is in progress (ids: {Ids})", filename, username, string.Join(", ", existingInProgressRecords.Select(t => t.Id)));
+ return null;
+ }
- try
- {
- Update(transfer);
- }
- finally
- {
- syncRoot.Release();
- }
+ /*
+ check the tracked upload dictionary in Soulseek.NET to see if it knows about this already
+ it shouldn't, if the slskd database doesn't. but things could get desynced
+ */
+ if (Client.Uploads.Any(u => u.Username == username && u.Filename == filename))
+ {
+ throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered");
}
+ /*
+ no existing transfers. next, check to see if they are requesting a file we are sharing
+
+ we do this after checking the database because database I/O is "cheaper" than disk and potentially
+ network (if we check a relay)
+ */
+ string host = default;
+ string localFilename = default;
+ long localFileLength = default;
+
+ try
+ {
+ (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: filename);
+ }
+ catch (NotFoundException)
+ {
+ Log.Information("Upload of {Filename} to {Username} {Rejected}: {Message}", filename, username, "REJECTED", "File not shared.");
+ throw new DownloadEnqueueException($"File not shared.");
+ }
+
+ Log.Debug("Resolved {Remote} to physical file {Physical} on host '{Host}'", filename, localFilename, host);
+
+ /*
+ we're cleared to enqueue! create a new transfer record, and automatically mark any existing records
+ we found as 'removed' to clean up the UI
+ */
+ var transfer = new Transfer()
+ {
+ Id = id,
+ Username = username,
+ Direction = TransferDirection.Upload,
+ Filename = filename, // important! use the remote filename
+ Size = localFileLength,
+ StartOffset = 0, // potentially updated later during handshaking
+ RequestedAt = DateTime.UtcNow,
+ State = TransferStates.Queued | TransferStates.Locally,
+ };
+
+ context.Add(transfer);
+
+ foreach (var record in existingRecords.Where(t => !t.Removed))
+ {
+ record.Removed = true;
+ context.Update(record);
+ Log.Debug("Marked existing upload record of {Filename} to {Username} removed (id: {Id})", filename, username, record.Id);
+ }
+
+ context.SaveChanges();
+
+ Log.Information("Successfully enqueued upload of {Filename} to {Username} (id: {Id})", filename, username, id);
+
+ // users with uploads must be watched so that we can keep informed of their online status, privileges, and
+ // statistics. this is so that we can accurately determine their effective group.
try
{
- // users with uploads must be watched so that we can keep informed of their online status, privileges, and
- // statistics. this is so that we can accurately determine their effective group.
if (!Users.IsWatched(username))
{
await Users.WatchAsync(username);
}
+ }
+ catch (Exception ex)
+ {
+ Log.Warning(ex, "Failed to watch user {Username}", username);
+ }
- var topts = new TransferOptions(
- stateChanged: (args) =>
- {
- Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, username, args.PreviousState, args.Transfer.State);
+ /*
+ schedule the upload immediately
- if (Application.IsShuttingDown)
- {
- Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", filename, username);
- return;
- }
+ Task.Run can fail due to thread pool exhaustion or OOM, and this *SHOULD* throw up the chain and
+ fail the enqueue request
+ */
+ _ = Task.Run(() => UploadAsync(transfer)).ContinueWith(task =>
+ {
+ if (task.IsCompletedSuccessfully)
+ {
+ Log.Information("Task for upload of {Filename} to {Username} completed successfully", filename, username);
+ return;
+ }
- transfer = transfer.WithSoulseekTransfer(args.Transfer);
+ /*
+ things that can cause us to arrive here:
- if (args.Transfer.State.HasFlag(TransferStates.Queued))
- {
- Queue.Enqueue(args.Transfer.Username, args.Transfer.Filename);
- transfer.EnqueuedAt = DateTime.UtcNow;
- }
+ * file not found (moved, deleted somehow)
+ * transfer record deleted somehow
+ * transfer record updated so that it's no longer in Queued | Locally
+ * Soulseek.NET already tracking an identical upload (slskd <> Soulseek.NET desync)
+ */
+ Log.Error(task.Exception, "Task for upload of {Filename} to {Username} did not complete successfully: {Error}", filename, username, task.Exception.Message);
- // todo: broadcast
- SynchronizedUpdate(transfer);
- },
- progressUpdated: (args) => rateLimiter.Invoke(() =>
- {
- transfer = transfer.WithSoulseekTransfer(args.Transfer);
-
- // todo: broadcast
- SynchronizedUpdate(transfer);
- }),
- seekInputStreamAutomatically: false,
- disposeInputStreamOnCompletion: true, // note: don't set this to false!
- governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct),
- reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act),
- slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename),
- slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename));
-
- if (host == Program.LocalHostName)
+ try
{
- var completedTransfer = await Client.UploadAsync(
- username,
- filename,
- size: localFileLength,
- inputStreamFactory: (startOffset) =>
- {
-#pragma warning disable S2930 // "IDisposables" should be disposed
- // disposeInputStreamOnCompletion takes care of this
- var stream = new FileStream(localFilename, FileMode.Open, FileAccess.Read);
-#pragma warning restore S2930 // "IDisposables" should be disposed
+ var transfer = Find(t => t.Id == id);
- stream.Seek(startOffset, SeekOrigin.Begin);
- return Task.FromResult((Stream)stream);
- },
- options: topts,
- cancellationToken: cts.Token);
+ if (transfer is not null)
+ {
+ transfer.EndedAt ??= DateTime.UtcNow;
+ transfer.Exception ??= task.Exception.Message;
+ transfer.State = TransferStates.Completed | transfer.State;
- transfer = transfer.WithSoulseekTransfer(completedTransfer);
+ Update(transfer);
+ }
}
- else
+ catch (Exception ex)
{
- var completedTransfer = await Client.UploadAsync(
- username,
- filename,
- size: localFileLength,
- inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename, startOffset, id),
- options: topts,
- cancellationToken: cts.Token);
-
- Relay.TryCloseFileStream(host, id);
-
- transfer = transfer.WithSoulseekTransfer(completedTransfer);
+ Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", id, ex.Message);
+ throw;
}
+ });
- // explicitly dispose the rate limiter to prevent updates from it beyond this point, which may overwrite the
- // final state
- rateLimiter.Dispose();
+ return transfer;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to enqueue upload of {Filename} to {Username}: {Message}", filename, username, ex.Message);
- // todo: broadcast
- SynchronizedUpdate(transfer, cancellable: false);
+ try
+ {
+ var transfer = Find(t => t.Id == id);
- EventBus.Raise(new UploadFileCompleteEvent
+ if (transfer is not null)
{
- Timestamp = transfer.EndedAt.Value,
- LocalFilename = localFilename,
- RemoteFilename = filename,
- Transfer = transfer,
- });
- }
- catch (OperationCanceledException ex)
- {
- transfer.EndedAt = DateTime.UtcNow;
- transfer.Exception = ex.Message;
- transfer.State = TransferStates.Completed | TransferStates.Cancelled;
+ transfer.EndedAt ??= DateTime.UtcNow;
- // todo: broadcast
- SynchronizedUpdate(transfer, cancellable: false);
+ // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
+ // exceptions in a database. when we encounter one of these, drop the first segment.
+ var m = ex.Message;
+ transfer.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;
- Relay.TryCloseFileStream(host, id, ex);
+ transfer.State = TransferStates.Completed | transfer.State;
- throw;
+ Update(transfer);
+ }
}
- catch (Exception ex)
+ catch (Exception innerEx)
{
- Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", filename, username, ex.Message);
-
- transfer.EndedAt = DateTime.UtcNow;
- transfer.State = TransferStates.Completed | TransferStates.Errored;
-
- // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
- // exceptions in a database. when we encounter one of these, drop the first segment.
- transfer.Exception = ex.Message.Contains(':') ? ex.Message.Substring(ex.Message.IndexOf(':') + 1).Trim() : ex.Message;
-
- // todo: broadcast
- SynchronizedUpdate(transfer, cancellable: false);
-
- Relay.TryCloseFileStream(host, id, ex);
+ Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, innerEx.Message);
throw;
}
- finally
+
+ throw;
+ }
+ finally
+ {
+ if (Locks.TryRemove(lockName, out _))
{
- CancellationTokens.TryRemove(id, out _);
+ Log.Debug("Released lock {LockName}", lockName);
}
- });
+ }
}
/// <summary>
@@ -651,5 +914,97 @@ namespace slskd.Transfers.Uploads
context.Update(transfer);
context.SaveChanges();
}
+
+ /// <summary>
+ /// Resolves a remote file's location and size from shares and potentially disk.
+ /// </summary>
+ /// <param name="remoteFilename">The file to resolve.</param>
+ /// <returns>The resolved host, filename (on disk), and length.</returns>
+ /// <exception cref="NotFoundException">Thrown if the file can't be located, either in a share or on disk.</exception>
+ private async Task<(string Host, string Filename, long Length)> ResolveFileInfoAsync(string remoteFilename)
+ {
+ string host;
+ string filename;
+ long length;
+
+ /*
+ locate the file and the stored details from shares.
+ the size returned here will be the size the remote client is expecting.
+
+ throws NotFoundException
+ */
+ (host, filename, length) = await Shares.ResolveFileAsync(remoteFilename);
+
+ Log.Debug("Resolved shared file {RemoteFilename} to host {Host} and file {ShareFilename} (length: {ShareLength})", remoteFilename, host, filename, length);
+
+ /*
+ if the file is hosted locally, do some quick I/O to check to see if the file still exists at the location
+ and of the size stored in the scan. the cost is negligible and this will keep transfers that are doomed
+ to fail out of our queue.
+ */
+ if (host == Program.LocalHostName)
+ {
+ var info = Files.ResolveFileInfo(filename);
+
+ // if the file doesn't exist we can't continue; shares have diverged from disk
+ if (!info.Exists)
+ {
+ Shares.RequestScan();
+ Log.Warning("The shared file '{File}' could not be located on disk. A share scan should be performed", filename);
+ throw new NotFoundException($"The file '{filename}' could not be located on disk. A share scan should be performed.");
+ }
+
+ // shares have diverged from disk, but we *MIGHT* be able to upload this file, if the remote client
+ // doesn't care that the size is exact. we definitely need to re-scan though.
+ if (info.Length != length)
+ {
+ Log.Warning("The length of shared file '{File}' differs between the share ({ShareSize}) and disk ({DiskSize}). A share scan should be performed", filename, length, info.Length);
+ Shares.RequestScan();
+ }
+
+ length = info.Length;
+ }
+ else if (!OptionsMonitor.CurrentValue.Flags.OptimisticRelayFileInfo)
+ {
+ /*
+ if the file is hosted on a relay agent and the user has set the pessimistic flag to true,
+ get the file info from the agent.
+
+ this was, at one time, the default behavior, but users complained that it caused a lot of timeouts
+ so now it is opt-in.
+ */
+ var (exists, relayLength) = await Relay.GetFileInfoAsync(agentName: host, remoteFilename);
+
+ if (!exists || relayLength <= 0)
+ {
+ // todo: force a remote scan
+ throw new NotFoundException($"The file '{remoteFilename}' could not be located on Agent {host}. A share scan should be performed.");
+ }
+
+ if (relayLength != length)
+ {
+ // todo: force a remote scan
+ Log.Warning("The length of shared file '{File}' on host {Host} differs between the share ({ShareSize}) and disk ({DiskSize}). A share scan should be performed", filename, host, length, relayLength);
+ }
+
+ length = relayLength;
+ }
+
+ return (host, filename, length);
+ }
+
+ private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default)
+ {
+ semaphore.Wait(cancellationToken);
+
+ try
+ {
+ Update(transfer);
+ }
+ finally
+ {
+ semaphore.Release();
+ }
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 7fed469a..4ed01a2d 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -69,7 +69,7 @@
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" />
<PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" />
- <PackageReference Include="Soulseek" Version="7.1.2" />
+ <PackageReference Include="Soulseek" Version="8.5.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 9ec8b5b9..8a097dce 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -13,7 +13,7 @@
"@codemirror/legacy-modes": "^6.0.0",
"@microsoft/signalr": "^7.0.7",
"@uiw/react-codemirror": "^4.2.4",
- "axios": "^0.30.0",
+ "axios": "^0.30.2",
"lz-string": "^1.4.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
@@ -3284,10 +3284,11 @@
}
},
"node_modules/@graphql-tools/url-loader/node_modules/ws": {
- "version": "8.16.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz",
- "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==",
+ "version": "8.18.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"dev": true,
+ "license": "MIT",
"engines": {
"node": ">=10.0.0"
},
@@ -3423,10 +3424,11 @@
}
},
"node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": {
- "version": "3.14.1",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
- "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
+ "version": "3.14.2",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
+ "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
@@ -5947,25 +5949,26 @@
}
},
"node_modules/axios": {
- "version": "0.30.0",
- "resolved": "https://registry.npmjs.org/axios/-/axios-0.30.0.tgz",
- "integrity": "sha512-Z4F3LjCgfjZz8BMYalWdMgAQUnEtKDmpwNHjh/C8pQZWde32TF64cqnSeyL3xD/aTIASRU30RHTNzRiV/NpGMg==",
+ "version": "0.30.2",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-0.30.2.tgz",
+ "integrity": "sha512-0pE4RQ4UQi1jKY6p7u6i1Tkzqmu+d+/tHS7Q7rKunWLB9WyilBTpHHpXzPNMDj5hTbK0B0PTLSz07yqMBiF6xg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.4",
- "form-data": "^4.0.0",
+ "form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/axios/node_modules/form-data": {
- "version": "4.0.2",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
- "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
+ "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@@ -10939,14 +10942,17 @@
}
},
"node_modules/form-data": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz",
- "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==",
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.4.tgz",
+ "integrity": "sha512-f0cRzm6dkyVYV3nPoooP8XlccPQukegwhAnpoLcXy+X+A8KfpGOoXwDr9FLZd3wzgLaBGQBE3lY93Zm/i1JvIQ==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
- "mime-types": "^2.1.12"
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
+ "mime-types": "^2.1.35"
},
"engines": {
"node": ">= 6"
@@ -13937,10 +13943,11 @@
}
},
"node_modules/js-yaml": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
- "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
},
@@ -19407,10 +19414,11 @@
}
},
"node_modules/svgo/node_modules/js-yaml": {
- "version": "3.14.1",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
- "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
+ "version": "3.14.2",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
+ "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
@@ -20691,10 +20699,11 @@
}
},
"node_modules/webpack-dev-server/node_modules/ws": {
- "version": "8.13.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz",
- "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==",
+ "version": "8.18.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"dev": true,
+ "license": "MIT",
"engines": {
"node": ">=10.0.0"
},
@@ -21315,9 +21324,10 @@
}
},
"node_modules/ws": {
- "version": "7.5.9",
- "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz",
- "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==",
+ "version": "7.5.10",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz",
+ "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==",
+ "license": "MIT",
"engines": {
"node": ">=8.3.0"
},
diff --git a/src/web/package.json b/src/web/package.json
index 46835e0e..73dde026 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -18,7 +18,7 @@
"@codemirror/legacy-modes": "^6.0.0",
"@microsoft/signalr": "^7.0.7",
"@uiw/react-codemirror": "^4.2.4",
- "axios": "^0.30.0",
+ "axios": "^0.30.2",
"lz-string": "^1.4.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css
index a3a2c83a..bd9a6f99 100644
--- a/src/web/src/components/System/System.css
+++ b/src/web/src/components/System/System.css
@@ -8,6 +8,10 @@
margin-bottom: 16px;
}
+.system .menu.tabular {
+ overflow: auto hidden;
+}
+
.logs-table, .events-table {
font-size: smaller;
}