diff options
Diffstat (limited to 'src')
24 files changed, 1276 insertions, 542 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index d8dab87c..c1e09d42 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -187,8 +187,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; @@ -219,6 +219,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; } @@ -374,18 +375,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), @@ -495,7 +502,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 @@ -529,211 +536,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> @@ -1381,12 +1403,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/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 352d23e9..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> @@ -1812,7 +1846,6 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [FileDoesNotExist] [AbsoluteFilePath] [RequiresRestart] public string Socket { get; init; } 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 0d879d0c..07d08fca 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; @@ -236,6 +238,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; } @@ -590,7 +593,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 @@ -605,9 +610,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); }) @@ -702,8 +710,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"))); @@ -1132,6 +1142,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) @@ -1178,6 +1212,7 @@ namespace slskd services.AddDbContextFactory<T>(options => { options.UseSqlite(connectionString); + options.AddInterceptors(new SqliteConnectionOpenedInterceptor()); if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) { @@ -1185,11 +1220,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/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 2207ac8c..d5c44c1a 100644 --- a/src/slskd/Telemetry/API/TelemetryController.cs +++ b/src/slskd/Telemetry/API/TelemetryController.cs @@ -57,7 +57,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/Telemetry/TelemetryService.cs b/src/slskd/Telemetry/TelemetryService.cs index c3d66196..1c124610 100644 --- a/src/slskd/Telemetry/TelemetryService.cs +++ b/src/slskd/Telemetry/TelemetryService.cs @@ -1,4 +1,4 @@ -// <copyright file="MetricsService.cs" company="slskd Team"> +// <copyright file="TelemetryService.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify diff --git a/src/slskd/Telemetry/Types/PrometheusMetric.cs b/src/slskd/Telemetry/Types/PrometheusMetric.cs index 53b8dc10..93ca6422 100644 --- a/src/slskd/Telemetry/Types/PrometheusMetric.cs +++ b/src/slskd/Telemetry/Types/PrometheusMetric.cs @@ -1,4 +1,4 @@ -// <copyright file="Types.cs" company="slskd Team"> +// <copyright file="PrometheusMetric.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify 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 ef8e84bf..9d0a8ed9 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> @@ -174,298 +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 require", nameof(files)); + throw new ArgumentException("At least one file is required", nameof(files)); } - return EnqueueAsyncInternal(username, files); + if (fileList.Count != fileList.Distinct().Count()) + { + throw new ArgumentException("Two or more files in request are duplicated", nameof(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; + } - Log.Debug("Priming connection for user {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false); - Log.Debug("Connection for user '{Username}' primed", username); + var maxTimeToWaitForEnqueueRequestAck = TimeSpan.FromMinutes(3); + var enqueueSemaphore = new SemaphoreSlim(initialCount: concurrentEnqueueRequests, maxCount: concurrentEnqueueRequests); - var thrownExceptions = new List<Exception>(); + /* + iterate over each of the files in the request. each file must be dispositioned as one of the following: - foreach (var file in files) + 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 + + 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! - var id = Guid.NewGuid(); + 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); + 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); + + 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); + } - var cts = new CancellationTokenSource(); - CancellationTokens.TryAdd(id, cts); + /* + create a TaskCompletionSource that we can await for one of the following: - var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); + 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 - // 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 () => + 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>(); + + // 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()); + + /* + 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); - - if (Application.IsShuttingDown) - { - Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", file.Filename, username); - return; - } + // satisfies condition #1; transfer is now remotely queued + 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) + // 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)) { - transfer.EnqueuedAt = DateTime.UtcNow; - waitUntilEnqueue.TrySetResult(true); + enqueuedTcs.TrySetResult(transfer); } - - SynchronizedUpdate(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) + else { - syncRoot.Wait(cts.Token); - - try - { - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) - { - // 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(); - } + enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); } - })); - - 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 + Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username); + + var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken: cts.Token)).ContinueWith(task => { - Timestamp = transfer.EndedAt.Value, - LocalFilename = finalFilename, - RemoteFilename = transfer.Filename, - Transfer = transfer, - }); + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); + return; + } - // 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.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); - if (!pendingDownloadsInDirectory.Any()) - { - EventBus.Raise(new DownloadDirectoryCompleteEvent + if (!TryFail(transferId, exception: task.Exception)) { - Timestamp = transfer.EndedAt.Value, - Username = transfer.Username, - LocalDirectoryName = destinationDirectory, - RemoteDirectoryName = remoteDirectoryName, - }); - } + 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(); - 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.Debug("Download Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadTask.Status); + + Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely); - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); + /* + wait for one of the four conditions to be true: - throw; + 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; + + Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", transfer.Filename, transfer.Username, state); } catch (Exception ex) { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", file.Filename, username, ex.Message); - - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; - - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); - - throw; + 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; + } - // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate? - if (ex is AggregateException aggEx) + 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); + + 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); } } @@ -643,12 +736,74 @@ 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; + t.Exception ??= exception.Message; + + 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; } @@ -663,5 +818,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/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6db9f6a5..4b35bffb 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -69,7 +69,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user. /// </summary> - /// <param name="transfer">The transfer to upload.</param> + /// <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> @@ -211,7 +211,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user. /// </summary> - /// <param name="transfer">The transfer to upload.</param> + /// <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> @@ -220,6 +220,13 @@ namespace slskd.Transfers.Uploads /// <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 localFileLength = default; + var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; if (!Locks.TryAdd(lockName, true)) @@ -228,104 +235,82 @@ namespace slskd.Transfers.Uploads return null; } - Transfer t = transfer; - /* - fetch an updated copy of the transfer record from the database; now that we are locked, we *should* - have exclusive access to this record - - 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 - */ - t = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + 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 - if (t.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {t.State}"); - } + failure to do so means records will get "stuck" in the database/on the UI - /* - 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 + additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot */ - if (Client.Uploads.Any(u => u.Username == t.Username && u.Filename == t.Filename)) - { - throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); - } - - // 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 (!Users.IsWatched(t.Username)) + Log.Debug("Acquired lock {LockName}", lockName); + + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + 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 (transfer.State != (TransferStates.Queued | TransferStates.Locally)) { - await Users.WatchAsync(t.Username); + throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to watch user {Username}", t.Username); - } - - var cts = new CancellationTokenSource(); - var syncRoot = new SemaphoreSlim(1, 1); - void SynchronizedUpdate(Transfer transfer, bool cancellable = true) - { - syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + /* + 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"); + } + // 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 { - Update(transfer); + if (!Users.IsWatched(transfer.Username)) + { + await Users.WatchAsync(transfer.Username); + } } - finally + catch (Exception ex) { - syncRoot.Release(); + Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); } - } - - string host = default; - string localFilename = default; - long localFileLength = default; - - /* - 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 - { - Log.Debug("Acquired lock {LockName}", lockName); - Log.Information("Initializing upload {Filename} to {Username}", t.Filename, t.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: t.Filename); + (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: transfer.Filename); - using var rateLimiter = new RateLimiter(250, flushOnDispose: true); + using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); var topts = new TransferOptions( stateChanged: (args) => { - Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, t.Username, args.PreviousState, args.Transfer.State); + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, 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("Upload update of {Filename} to {Username} not persisted; app is shutting down", t.Filename, t.Username); + Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); return; } transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); }, progressUpdated: (args) => rateLimiter.Invoke(() => { @@ -334,28 +319,32 @@ namespace slskd.Transfers.Uploads // being made after the transfer is completed, causing them to appear 'stuck' if (transfer.State == TransferStates.InProgress) { - syncRoot.Wait(cts.Token); - - try + // 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)) { - // 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; - - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) + 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, args.Transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, args.Transfer.AverageSpeed)); + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + } + finally + { + syncRoot.Release(); } } - finally + else { - syncRoot.Release(); + 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); } } }), @@ -367,20 +356,20 @@ namespace slskd.Transfers.Uploads slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); // register the cancellation token - CancellationTokens.TryAdd(t.Id, cts); + CancellationTokens.TryAdd(transfer.Id, cts); // add the transfer to the UploadQueue so that it can become eligible for selection - Queue.Enqueue(t.Username, t.Filename); + Queue.Enqueue(transfer.Username, transfer.Filename); transfer.EnqueuedAt = DateTime.UtcNow; - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); Soulseek.Transfer completedTransfer; if (host == Program.LocalHostName) { completedTransfer = await Client.UploadAsync( - username: t.Username, - remoteFilename: t.Filename, + username: transfer.Username, + remoteFilename: transfer.Filename, size: localFileLength, inputStreamFactory: (startOffset) => { @@ -398,14 +387,14 @@ namespace slskd.Transfers.Uploads else { completedTransfer = await Client.UploadAsync( - username: t.Username, - remoteFilename: t.Filename, + username: transfer.Username, + remoteFilename: transfer.Filename, size: localFileLength, - inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: t.Filename, startOffset, id: t.Id), + inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: transfer.Filename, startOffset, id: transfer.Id), options: topts, cancellationToken: cts.Token); - Relay.TryCloseFileStream(host, id: t.Id); + Relay.TryCloseFileStream(host, id: transfer.Id); } // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we @@ -417,13 +406,13 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); EventBus.Raise(new UploadFileCompleteEvent { Timestamp = transfer.EndedAt.Value, LocalFilename = localFilename, - RemoteFilename = t.Filename, + RemoteFilename = transfer.Filename, Transfer = transfer, }); @@ -435,31 +424,38 @@ namespace slskd.Transfers.Uploads transfer.Exception = "File could not be found"; transfer.State = TransferStates.Completed | TransferStates.Aborted; - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } - catch (OperationCanceledException ex) + catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) { transfer.EndedAt = DateTime.UtcNow; transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Cancelled; + transfer.State = TransferStates.Completed; + + transfer.State |= ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } catch (Exception ex) { - Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", t.Filename, t.Username, ex.Message); + 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, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } @@ -469,7 +465,7 @@ namespace slskd.Transfers.Uploads { try { - Relay.TryCloseFileStream(host, id: t.Id); + Relay.TryCloseFileStream(host, id: transfer.Id); } catch { @@ -482,16 +478,16 @@ namespace slskd.Transfers.Uploads Locks.TryRemove(lockName, out _); Log.Debug("Released lock {LockName}", lockName); - CancellationTokens.TryRemove(t.Id, out _); + 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: t.Username, filename: t.Filename); + Queue.TryComplete(username: transfer.Username, filename: transfer.Filename); } catch (Exception ex) { - Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", t.Filename, t.Username, ex.Message); + Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); throw; } } @@ -505,11 +501,21 @@ namespace slskd.Transfers.Uploads /// <returns>The operation context.</returns> public async Task<Transfer> EnqueueAsync(string username, string filename) { + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentNullException(nameof(username), "Username is required"); + } + + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentNullException(nameof(filename), "Filename is required"); + } + var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}"; if (!Locks.TryAdd(lockName, true)) { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + Log.Debug("Ignoring concurrent upload enqueue attempt; lock {LockName} already held", lockName); return null; } @@ -600,7 +606,7 @@ namespace slskd.Transfers.Uploads { record.Removed = true; context.Update(record); - Log.Debug("Marked existing upload record {Filename} to {Username} removed (id: {Id})", filename, username, record.Id); + Log.Debug("Marked existing upload record of {Filename} to {Username} removed (id: {Id})", filename, username, record.Id); } context.SaveChanges(); @@ -694,8 +700,10 @@ namespace slskd.Transfers.Uploads } finally { - Locks.TryRemove(lockName, out _); - Log.Debug("Released lock {LockName}", lockName); + if (Locks.TryRemove(lockName, out _)) + { + Log.Debug("Released lock {LockName}", lockName); + } } } @@ -979,5 +987,19 @@ namespace slskd.Transfers.Uploads 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 d6e977cb..63dd6937 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,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="8.1.1" /> + <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 64bebae1..8a097dce 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -3424,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" @@ -13942,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" }, @@ -19412,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" 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; } |
