aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--config/slskd.example.yml47
-rw-r--r--docs/config.md2
-rw-r--r--src/slskd/Application.cs34
-rw-r--r--src/slskd/Core/Options.cs61
-rw-r--r--src/slskd/Integrations/Scripts/ScriptService.cs125
-rw-r--r--src/slskd/Program.cs7
-rw-r--r--src/slskd/Search/API/Controllers/SearchesController.cs9
-rw-r--r--src/slskd/Search/SearchService.cs127
-rw-r--r--src/web/package-lock.json7
-rw-r--r--src/web/src/components/Search/Searches.jsx4
10 files changed, 332 insertions, 91 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml
index dd164084..e76af51c 100644
--- a/config/slskd.example.yml
+++ b/config/slskd.example.yml
@@ -234,15 +234,50 @@
# retry:
# attempts: 3
# scripts:
-# my_post_download_script:
+# run_command_with_linux_system_shell: # automatically uses the executable defined in $SHELL
# on:
# - DownloadFileComplete
-# - DownloadDirectoryComplete
-# run: data/my_script.sh --json-to-process $EVENT
-# my_logging_script:
+# run:
+# command: 'echo "$SLSKD_SCRIPT_DATA" >> linux_system_shell.txt'
+# run_with_sh:
# on:
-# - All
-# run: data/log_slskd_events.sh $DATA
+# - DownloadFileComplete
+# run:
+# executable: /bin/sh
+# args: '-c "echo $SLSKD_SCRIPT_DATA >> linux_sh.txt"'
+# run_with_sh_and_args_list:
+# on:
+# - DownloadFileComplete
+# run:
+# executable: /bin/sh
+# arglist:
+# - -c
+# - echo $SLSKD_SCRIPT_DATA >> linux_sh_and_args_list.txt
+# run_command_with_windows_system_shell: # automatically uses cmd.exe (included with all Windows installs)
+# on:
+# - DownloadFileComplete
+# run:
+# command: 'echo "%SLSKD_SCRIPT_DATA%" >> windows_system_shell.txt'
+# run_with_windows_cmd:
+# on:
+# - DownloadFileComplete
+# run:
+# executable: cmd.exe
+# args: '/c "echo "%SLSKD_SCRIPT_DATA%" >> windows_cmd.txt"'
+# run_with_windows_git_bash:
+# on:
+# - DownloadFileComplete
+# run:
+# executable: C:\Program Files\Git\bin\bash.exe
+# args: '-c "echo "$SLSKD_SCRIPT_DATA" >> windows_git_bash.txt"'
+# run_with_windows_cmd_and_args_list:
+# on:
+# - DownloadFileComplete
+# run:
+# executable: cmd.exe
+# arglist:
+# - /c
+# - 'echo "%SLSKD_SCRIPT_DATA%" >> windows_cmd_and_args_list.txt'
# ftp:
# enabled: false
# address: ~
diff --git a/docs/config.md b/docs/config.md
index 4d8764a5..92798196 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -935,7 +935,7 @@ retention:
files:
complete: 20160 # 2 weeks
incomplete: 43200 # 30 days
- logs: 259200 # 180 days
+ logs: 180 # days
```
# Integrations
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 05f62902..791cf245 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -307,34 +307,60 @@ namespace slskd
{
Log.Information("Application started");
+ Log.Debug("Cleaning up any dangling records");
+
// if the application shut down "uncleanly", transfers may need to be cleaned up. we deliberately don't allow these
// records to be updated if the application has started to shut down so that we can do this cleanup and properly
// disposition them as having failed due to an application shutdown, instead of some random exception thrown while
// things are being disposed.
- var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed), includeRemoved: false)
- .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434
+ var activeUploads = Transfers.Uploads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true)
+ .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280
.ToList();
foreach (var upload in activeUploads)
{
Log.Debug("Cleaning up dangling upload {Filename} to {Username}", upload.Filename, upload.Username);
upload.State = TransferStates.Completed | TransferStates.Errored;
+ upload.EndedAt = DateTime.UtcNow;
upload.Exception = ApplicationShutdownTransferExceptionMessage;
Transfers.Uploads.Update(upload);
}
- var activeDownloads = Transfers.Downloads.List(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed)
- .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434
+ var activeDownloads = Transfers.Downloads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true)
+ .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) // https://github.com/slskd/slskd/issues/1280
.ToList();
foreach (var download in activeDownloads)
{
Log.Debug("Cleaning up dangling download {Filename} from {Username}", download.Filename, download.Username);
download.State = TransferStates.Completed | TransferStates.Errored;
+ download.EndedAt = DateTime.UtcNow;
download.Exception = ApplicationShutdownTransferExceptionMessage;
Transfers.Downloads.Update(download);
}
+ /*
+ search records can be left 'dangling' as well. responses are held in memory and saved to the database
+ when the search is complete, so when a search 'dangles' all responses have been lost. to avoid discrepancies,
+ we need to zero the response and file counts as well as set the state and EndedAt.
+ */
+ var activeSearches = (await Search.ListAsync(s => s.EndedAt == null || !s.State.HasFlag(SearchStates.Completed)))
+ .Where(s => s.EndedAt == null || !s.State.HasFlag(SearchStates.Completed)) // https://github.com/slskd/slskd/issues/1280
+ .ToList();
+
+ foreach (var search in activeSearches)
+ {
+ Log.Debug("Cleaning up dangling search {Query} started {StartedAt}", search.SearchText, search.StartedAt);
+ search.Responses = [];
+ search.ResponseCount = 0;
+ search.FileCount = 0;
+ search.LockedFileCount = 0;
+ search.State = SearchStates.Completed | SearchStates.TimedOut;
+ search.EndedAt = DateTime.UtcNow;
+
+ Search.Update(search);
+ }
+
// save the ids of any downloads that were active, so we can re-enqueue them after we've connected and logged in.
// we need to check the database before we re-request to make sure the user didn't remove them from the UI while
// the application was running, but before it was logged in. so just save the ids.
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index ff9cc407..266d04aa 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -2107,14 +2107,10 @@ namespace slskd
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
- var results = new List<ValidationResult>();
-
if (!Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
- results.Add(new ValidationResult($"The {nameof(Url)} field must contain a fully qualified URL, including protocol (e.g. http:// or https://)"));
+ yield return new ValidationResult($"The {nameof(Url)} field must contain a fully qualified URL, including protocol (e.g. http:// or https://)");
}
-
- return results;
}
}
@@ -2161,9 +2157,58 @@ namespace slskd
/// <summary>
/// Gets the shell script to invoke.
/// </summary>
- [StringLength(int.MaxValue, MinimumLength = 1)]
- [NotNullOrWhiteSpace]
- public string Run { get; init; }
+ public ScriptRunOptions Run { get; init; } = new ScriptRunOptions();
+ }
+
+ /// <summary>
+ /// Script run options.
+ /// </summary>
+ public class ScriptRunOptions : IValidatableObject
+ {
+ /// <summary>
+ /// Gets the shell command to run.
+ /// </summary>
+ public string Command { get; init; }
+
+ /// <summary>
+ /// Gets the executable to start.
+ /// </summary>
+ public string Executable { get; init; }
+
+ /// <summary>
+ /// Gets the arguments to pass to the executable.
+ /// </summary>
+ /// <remarks>
+ /// Mutually exclusive with <see cref="Arglist"/>.
+ /// </remarks>
+ public string Args { get; init; }
+
+ /// <summary>
+ /// Gets the list of arguments to pass to the executable.
+ /// </summary>
+ /// <remarks>
+ /// Mutually exclusive with <see cref="Args"/>.
+ /// </remarks>
+ public string[] Arglist { get; init; } = null;
+
+ public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
+ {
+ var cmdIsSet = !string.IsNullOrWhiteSpace(Command);
+ var exeIsSet = !string.IsNullOrWhiteSpace(Executable);
+
+ if ((cmdIsSet && exeIsSet) || (!cmdIsSet && !exeIsSet))
+ {
+ yield return new ValidationResult($"One and only one of the fields {nameof(Command)} or {nameof(Executable)} may be specified for a single script. If you intend to use the system shell, omit 'executable'. If you intend to use an executable other than the system shell, omit 'command' and specify either 'args' or 'args_list'.");
+ }
+
+ var argsIsSet = !string.IsNullOrWhiteSpace(Args);
+ var argsListIsSet = Arglist is not null;
+
+ if (argsIsSet && argsListIsSet)
+ {
+ yield return new ValidationResult($"Only one of the fields {nameof(Args)} or {nameof(Arglist)} may be specified for a single script. Specify 'args' if you intend to construct a single quoted string yourself, and specify 'args_list' if you'd like slskd to handle quoting for you.");
+ }
+ }
}
/// <summary>
diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs
index 227f2fb1..05769a6d 100644
--- a/src/slskd/Integrations/Scripts/ScriptService.cs
+++ b/src/slskd/Integrations/Scripts/ScriptService.cs
@@ -39,12 +39,31 @@ public class ScriptService
Events.Subscribe<Event>(nameof(ScriptService), HandleEvent);
+ if (OperatingSystem.IsWindows())
+ {
+ DefaultExecutable = "cmd.exe";
+ DefaultCommandPrefix = "/c";
+ }
+ else
+ {
+ DefaultExecutable = Environment.GetEnvironmentVariable("SHELL");
+ DefaultCommandPrefix = "-c";
+
+ if (string.IsNullOrEmpty(DefaultExecutable))
+ {
+ Log.Warning("Unable to determine default script executable ($SHELL is missing or blank); any user-defined scripts that do not specify an executable will fail");
+ }
+ }
+
+ Log.Information("Set default script executable to '{DefaultExecutable}'", DefaultExecutable);
Log.Debug("{Service} initialized", nameof(ScriptService));
}
private ILogger Log { get; } = Serilog.Log.ForContext<ScriptService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
private EventBus Events { get; }
+ private string DefaultExecutable { get; }
+ private string DefaultCommandPrefix { get; }
private async Task HandleEvent(Event data)
{
@@ -64,44 +83,92 @@ public class ScriptService
_ = Task.Run(() =>
{
Process process = default;
+ var processId = Guid.NewGuid();
+ // there are three 'modes' that we can use to execute a script, which are detailed below.
+ // the mode is negotiated based on the script config, and we rely on the validation in Options
+ // to enforce mututal exclusivity and prevent a user from supplying an invalid config
try
{
var run = script.Value.Run;
+ var executable = run.Executable ?? DefaultExecutable;
- // split the string into at most 2 parts, leaving part [0] the executable and part [1] the rest of the string, but possibly null
- var parts = run.Split(" ", count: 2, options: StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.RemoveEmptyEntries);
-
- var executable = parts[0];
- string args = default;
-
- if (parts.Length > 1)
+ if (string.IsNullOrEmpty(executable))
{
- args = parts[1].Replace("$DATA", data.ToJson());
+ Log.Warning("Script '{Script}' will not be run: unable to determine script executable. Update the script configuration, or set your operating system's SHELL envar.");
+ return;
}
- Log.Debug("Running script '{Script}': {Run}", script.Key, run);
- var sw = Stopwatch.StartNew();
-
- process = new Process()
+ if (!string.IsNullOrEmpty(run.Command))
{
- StartInfo = new ProcessStartInfo(fileName: executable)
+ // 'command' mode takes precedence over 'executable' mode
+ // run the system shell and ensure the specified command is prefixed with the correct flag
+ // this is designed to be the 'pit of success' for this feature that will work for most users,
+ // who most likely have not read the docs and expect this to work like a command line.
+ // users are on the hook for properly (and safely) quoting arguments
+ Log.Debug("Running script '{Script}' in 'command mode'", script.Key);
+
+ process = new Process()
{
- UseShellExecute = false,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- RedirectStandardInput = true,
- },
- };
-
- process.Start();
-
- if (args is not null)
+ StartInfo = new ProcessStartInfo(fileName: executable)
+ {
+ WorkingDirectory = Program.ScriptDirectory,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ Arguments = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} \"{run.Command.Trim('"')}\"",
+ },
+ };
+ }
+ else if (run.Arglist is not null)
{
- process.StandardInput.WriteLine(args);
+ // 'args list' mode takes precedence over 'args' mode
+ // the supplied list of args will be passed to the constructor of ProcessStartInfo, which is
+ // curiously the only way to pass a list of args (instead of a string). if no executable has been
+ // specified, the system shell is used. this mode is for maximalists who know what they are doing
+ // and want granular control
+ Log.Debug("Running script '{Script}' in 'args list mode'", script.Key);
+
+ process = new Process()
+ {
+ StartInfo = new ProcessStartInfo(
+ fileName: executable,
+ arguments: run.Arglist)
+ {
+ WorkingDirectory = Program.ScriptDirectory,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ },
+ };
+ }
+ else
+ {
+ // 'args' mode is the default mode
+ // run the specified executable, or if not specified, the system shell. pass the args string
+ // (which may be empty or null) to ProcessStartInfo
+ Log.Debug("Running script '{Script}' in 'args mode'", script.Key);
+ process = new Process()
+ {
+ StartInfo = new ProcessStartInfo(fileName: executable)
+ {
+ WorkingDirectory = Program.ScriptDirectory,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ Arguments = run.Args,
+ },
+ };
}
- process.StandardInput.WriteLine("exit");
+ Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, run.Args ?? string.Join(' ', run.Arglist ?? []), processId);
+ var sw = Stopwatch.StartNew();
+
+ process.StartInfo.EnvironmentVariables["SLSKD_SCRIPT_DATA"] = data.ToJson();
+ process.Start();
process.WaitForExit();
sw.Stop();
@@ -116,21 +183,23 @@ public class ScriptService
var result = process.StandardOutput.ReadToEnd();
var resultAsLines = result.Split(["\r\n", "\r", "\n"], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
- Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output}", script.Key, sw.ElapsedMilliseconds, resultAsLines);
+ Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output} (id: {ProcessId})", script.Key, sw.ElapsedMilliseconds, resultAsLines, processId);
}
catch (Exception ex)
{
- Log.Warning(ex, "Failed to run script '{Script}' for event type {Event}: {Message}", script.Key, data.Type, ex.Message);
+ Log.Warning("Failed to run script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId);
+ Log.Debug(ex, "Failed to run script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId);
}
finally
{
try
{
process?.Close();
+ process?.Dispose();
}
catch (Exception ex)
{
- Log.Warning(ex, "Failed to clean up process started from script '{Script}' for event type {Event}: {Message}", script.Key, data.Type, ex.Message);
+ Log.Warning(ex, "Failed to clean up process started from script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId);
}
}
});
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 49b01516..b7fa47d2 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -208,6 +208,11 @@ namespace slskd
public static string LogDirectory { get; private set; } = null;
/// <summary>
+ /// Gets the path where user-defined scripts are stored.
+ /// </summary>
+ public static string ScriptDirectory { get; private set; } = null;
+
+ /// <summary>
/// Gets a buffer containing the last few log events.
/// </summary>
public static ConcurrentFixedSizeQueue<LogRecord> LogBuffer { get; } = new ConcurrentFixedSizeQueue<LogRecord>(size: 100);
@@ -332,6 +337,7 @@ namespace slskd
AppDirectory ??= DefaultAppDirectory;
DataDirectory = Path.Combine(AppDirectory, "data");
LogDirectory = Path.Combine(AppDirectory, "logs");
+ ScriptDirectory = Path.Combine(AppDirectory, "scripts");
DefaultConfigurationFile = Path.Combine(AppDirectory, $"{AppName}.yml");
DefaultDownloadsDirectory = Path.Combine(AppDirectory, "downloads");
@@ -347,6 +353,7 @@ namespace slskd
{
VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true);
VerifyDirectory(DataDirectory, createIfMissing: true, verifyWriteable: true);
+ VerifyDirectory(ScriptDirectory, createIfMissing: true, verifyWriteable: false);
VerifyDirectory(DefaultDownloadsDirectory, createIfMissing: true, verifyWriteable: true);
VerifyDirectory(DefaultIncompleteDirectory, createIfMissing: true, verifyWriteable: true);
}
diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs
index d6d96bbe..58e1fe37 100644
--- a/src/slskd/Search/API/Controllers/SearchesController.cs
+++ b/src/slskd/Search/API/Controllers/SearchesController.cs
@@ -24,6 +24,7 @@ namespace slskd.Search.API
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+ using Serilog;
using SearchQuery = Soulseek.SearchQuery;
using SearchScope = Soulseek.SearchScope;
@@ -50,6 +51,7 @@ namespace slskd.Search.API
private ISearchService Searches { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
+ private ILogger Log { get; set; } = Serilog.Log.ForContext<SearchesController>();
/// <summary>
/// Performs a search for the specified <paramref name="request"/>.
@@ -83,12 +85,19 @@ namespace slskd.Search.API
}
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);
+ }
return Ok(search);
}
diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs
index 809647b2..b4864918 100644
--- a/src/slskd/Search/SearchService.cs
+++ b/src/slskd/Search/SearchService.cs
@@ -65,6 +65,15 @@ namespace slskd.Search
Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null);
/// <summary>
+ /// Updates the specified <paramref name="search"/>.
+ /// </summary>
+ /// <remark>
+ /// Round-trips the database; use accordingly.
+ /// </remark>
+ /// <param name="search">The search to update.</param>
+ void Update(Search search);
+
+ /// <summary>
/// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>.
/// </summary>
/// <param name="id">A unique identifier for the search.</param>
@@ -192,6 +201,17 @@ namespace slskd.Search
}
/// <summary>
+ /// Updates the specified <paramref name="search"/>.
+ /// </summary>
+ /// <param name="search">The search to update.</param>
+ public void Update(Search search)
+ {
+ using var context = ContextFactory.CreateDbContext();
+ context.Update(search);
+ context.SaveChanges();
+ }
+
+ /// <summary>
/// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>.
/// </summary>
/// <param name="id">A unique identifier for the search.</param>
@@ -208,6 +228,8 @@ namespace slskd.Search
var rateLimiter = new RateLimiter(250);
+ // initialize the search record, save it to the database, and broadcast the creation
+ // we do this so the UI has some feedback to show to the user that we've gotten their request
var search = new Search()
{
SearchText = query.SearchText,
@@ -221,14 +243,11 @@ namespace slskd.Search
context.Add(search);
context.SaveChanges();
- List<SearchResponse> responses = new();
+ await SearchHub.BroadcastCreateAsync(search);
- void UpdateAndSaveChanges(Search search)
- {
- using var context = ContextFactory.CreateDbContext();
- context.Update(search);
- context.SaveChanges();
- }
+ // initialize the list of responses that we'll use to accumulate them
+ // populated by the responseHandler we pass to SearchAsync
+ List<SearchResponse> responses = new();
options ??= new SearchOptions();
options = options.WithActions(
@@ -236,7 +255,7 @@ namespace slskd.Search
{
search = search.WithSoulseekSearch(args.Search);
SearchHub.BroadcastUpdateAsync(search);
- UpdateAndSaveChanges(search);
+ Update(search);
},
responseReceived: (args) => rateLimiter.Invoke(() =>
{
@@ -250,50 +269,78 @@ namespace slskd.Search
// note that we're not actually doing anything with the response here, that's happening in the
// response handler. we're only updating counts here.
SearchHub.BroadcastUpdateAsync(search);
- UpdateAndSaveChanges(search);
+ Update(search);
}));
- var soulseekSearchTask = Client.SearchAsync(
- query,
- responseHandler: (response) => responses.Add(response),
- scope,
- token,
- options,
- cancellationToken: cancellationTokenSource.Token);
-
- _ = Task.Run(async () =>
+ try
{
- try
- {
- var soulseekSearch = await soulseekSearchTask;
- search = search.WithSoulseekSearch(soulseekSearch);
- }
- finally
+ // initiate the search. this can throw at invocation if there's a problem with
+ // the client state (e.g. disconnected) or a problem with the search (e.g. no terms)
+ var soulseekSearchTask = Client.SearchAsync(
+ query,
+ responseHandler: (response) => responses.Add(response),
+ scope,
+ token,
+ options,
+ cancellationToken: cancellationTokenSource.Token);
+
+ // seach looks ok so far; let the rest of the logic run asynchronously
+ // on a background thread. this logic needs to clean up after itself and
+ // update the search record to accurately reflect the final state
+ _ = Task.Run(async () =>
{
- rateLimiter.Dispose();
- CancellationTokens.TryRemove(id, out _);
-
try
{
- search.EndedAt = DateTime.UtcNow;
- search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r));
-
- UpdateAndSaveChanges(search);
-
- // zero responses before broadcasting, as we don't want to blast this
- // data out over the SignalR socket
- await SearchHub.BroadcastUpdateAsync(search with { Responses = [] });
+ var soulseekSearch = await soulseekSearchTask;
+ search = search.WithSoulseekSearch(soulseekSearch);
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id);
+ Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message);
+ search.State = SearchStates.Completed | SearchStates.Errored;
}
- }
- });
+ finally
+ {
+ rateLimiter.Dispose();
+ CancellationTokens.TryRemove(id, out _);
+
+ try
+ {
+ search.EndedAt = DateTime.UtcNow;
+ search.Responses = responses.Select(r => Response.FromSoulseekSearchResponse(r));
+
+ Update(search);
+
+ // zero responses before broadcasting, as we don't want to blast this
+ // data out over the SignalR socket
+ await SearchHub.BroadcastUpdateAsync(search with { Responses = [] });
+ }
+ catch (Exception ex)
+ {
+ // record may be left 'hanging' and will need to be cleaned up at the next boot
+ Log.Error(ex, "Failed to persist search for {SearchQuery} ({Id})", query, id);
+ }
+ }
+ });
- await SearchHub.BroadcastCreateAsync(search);
+ await SearchHub.BroadcastUpdateAsync(search);
+
+ return search;
+ }
+ catch (Exception ex)
+ {
+ // we'll end up here if the initial call throws for an ArgumentException, InvalidOperationException if
+ // the app isn't connected, and a few other straightforward issues that arise before even requesting the search
+ Log.Error(ex, "Failed to execute search {Search}: {Message}", new { query, scope, options }, ex.Message);
- return search;
+ search.State = SearchStates.Completed | SearchStates.Errored;
+ search.EndedAt = search.StartedAt;
+ Update(search);
+
+ await SearchHub.BroadcastUpdateAsync(search with { Responses = [] });
+
+ throw;
+ }
}
/// <summary>
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 912ea6e9..a61bca8f 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -18432,10 +18432,11 @@
"dev": true
},
"node_modules/serialize-javascript": {
- "version": "6.0.1",
- "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.1.tgz",
- "integrity": "sha512-owoXEFjWRllis8/M1Q+Cw5k8ZH40e3zhp/ovX+Xr/vi1qj6QesbyXXViFbpNvWvPNAD62SutwEXavefrLJWj7w==",
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz",
+ "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==",
"dev": true,
+ "license": "BSD-3-Clause",
"dependencies": {
"randombytes": "^2.1.0"
}
diff --git a/src/web/src/components/Search/Searches.jsx b/src/web/src/components/Search/Searches.jsx
index 471f833d..d50462ba 100644
--- a/src/web/src/components/Search/Searches.jsx
+++ b/src/web/src/components/Search/Searches.jsx
@@ -72,7 +72,9 @@ const Searches = ({ server } = {}) => {
});
});
- searchHub.on('create', () => {});
+ searchHub.on('create', (search) => {
+ onUpdate((old) => ({ ...old, [search.id]: search }));
+ });
searchHub.onreconnecting((connectionError) =>
onConnectionError(connectionError?.message ?? 'Disconnected'),