From e21eb94376f242145b07b49c923f2f997d83611c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Oct 2024 18:35:52 -0500 Subject: stub webhook configuration --- config/slskd.example.yml | 12 +++++++++ src/slskd/Core/Options.cs | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 7dd6450b..a7336d93 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -213,6 +213,18 @@ # username: ~ # password: ~ # integration: +# webhooks: +# my_webhook: +# on: +# - DownloadFileComplete +# call: +# url: http://192.168.1.42:8080/slskd_webhook +# headers: +# - name: x-api-key +# value: foobar1234 +# - name: user-agent +# value: slskd/1.0 +# ignore_certificate_errors: true # scripts: # my_post_download_script: # on: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 306f9b87..cca24ee9 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2005,6 +2005,12 @@ namespace slskd /// public class IntegrationOptions { + /// + /// Gets webhook configuration. + /// + [Validate] + public Dictionary Webhooks { get; init; } = []; + /// /// Gets script configuration. /// @@ -2023,6 +2029,66 @@ namespace slskd [Validate] public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); + /// + /// Webhook configuration. + /// + public class WebhookOptions + { + /// + /// Gets the list of Event types that trigger the webhook. + /// + [Enum(typeof(EventType))] + public string[] On { get; init; } = Array.Empty(); + + /// + /// Gets details about the webhook call. + /// + [Validate] + public WebhookDetails Call { get; init; } = new WebhookDetails(); + } + + /// + /// Webhook details. + /// + public class WebhookDetails : IValidatableObject + { + /// + /// Gets the fully qualified URL for the webhook. + /// + [NotNullOrWhiteSpace] + public string Url { get; init; } + + /// + /// Gets the HTTP headers to include with the webhook. + /// + [Validate] + public IEnumerable Headers { get; init; } = []; + + /// + /// Gets a value indicating whether HTTPS certificate errors should be ignored. + /// + public bool IgnoreCertificateErrors { get; init; } = false; + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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://)")); + } + + return results; + } + } + + public class WebhookDetailHeader + { + [NotNullOrWhiteSpace] + public string Name { get; init; } + public string Value { get; init; } + } + /// /// Script configuration. /// -- cgit v1.2.3 From 88955fb1e597b08d802710063cd40da987c44d78 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Oct 2024 20:18:34 -0500 Subject: update ValidationAttribute to work with arrays --- src/slskd/Common/Validation/ValidateAttribute.cs | 36 +++++++++++++++++++----- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/slskd/Common/Validation/ValidateAttribute.cs b/src/slskd/Common/Validation/ValidateAttribute.cs index c7efaa92..540e61bc 100644 --- a/src/slskd/Common/Validation/ValidateAttribute.cs +++ b/src/slskd/Common/Validation/ValidateAttribute.cs @@ -17,6 +17,7 @@ namespace slskd.Validation { + using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -34,22 +35,43 @@ namespace slskd.Validation return ValidationResult.Success; } + // note: here's a great place to log the type and value if there are issues: + // Console.WriteLine($"{value.GetType()}: {value.ToJson()}"); var results = new List(); var context = new ValidationContext(value, null, null); - if (value.IsDictionary()) + // we should only be using dictionaries and arrays (e.g. []), not IEnumerable, because the YAML library + // somehow has nondeterministic behavior, sometimes turning YAML arrays into arrays, and sometimes List + // this could be handled by checking for List but let's just keep it simple and remember to use arrays + if (value.IsDictionary() || value is Array) { var compositeResults = new CompositeValidationResult(validationContext.DisplayName); - // given the context in this application, key type should never be anything but a string - foreach (string key in ((IDictionary)value).Keys) + if (value.IsDictionary()) { - var val = ((IDictionary)value)[key]; - var result = IsValid(val, new ValidationContext(val, null, null)); + // given the context in this application, key type should never be anything but a string + foreach (string key in ((IDictionary)value).Keys) + { + var val = ((IDictionary)value)[key]; + var result = IsValid(val, new ValidationContext(val, null, null)); - if (result != ValidationResult.Success) + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + } + } + } + else if (value is Array array) + { + for (int i = 0; i < array.Length; i++) { - compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + var val = array.GetValue(i); + var result = IsValid(val, new ValidationContext(val, null, null)); + + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(i.ToString(), new[] { result }.ToList())); + } } } -- cgit v1.2.3 From b94dfe45ad62b3fa6cad0e6358e5fcba49ff7d37 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Oct 2024 20:18:57 -0500 Subject: use an array for headers or everything breaks --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cca24ee9..a9d6aeb8 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2062,7 +2062,7 @@ namespace slskd /// Gets the HTTP headers to include with the webhook. /// [Validate] - public IEnumerable Headers { get; init; } = []; + public WebhookDetailHeader[] Headers { get; init; } = []; /// /// Gets a value indicating whether HTTPS certificate errors should be ignored. -- cgit v1.2.3 From 81a771c24d8957c8a9aca0d75987c4033d6c951d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Oct 2024 20:19:17 -0500 Subject: stub WebhookService --- src/slskd/Integrations/Webhooks/WebhookService.cs | 63 +++++++++++++++++++++++ src/slskd/Program.cs | 3 ++ 2 files changed, 66 insertions(+) create mode 100644 src/slskd/Integrations/Webhooks/WebhookService.cs diff --git a/src/slskd/Integrations/Webhooks/WebhookService.cs b/src/slskd/Integrations/Webhooks/WebhookService.cs new file mode 100644 index 00000000..9ed0c947 --- /dev/null +++ b/src/slskd/Integrations/Webhooks/WebhookService.cs @@ -0,0 +1,63 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.Webhooks; + +using System; +using System.Linq; +using System.Threading.Tasks; +using Serilog; +using slskd.Events; + +public class WebhookService +{ + public WebhookService(EventBus eventBus, IOptionsMonitor optionsMonitor) + { + Events = eventBus; + OptionsMonitor = optionsMonitor; + + Events.Subscribe(nameof(WebhookService), HandleEvent); + + Log.Debug("{Service} initialized", nameof(WebhookService)); + Log.Warning("Webhook config: {Config}", OptionsMonitor.CurrentValue.Integration.Webhooks.ToJson()); + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IOptionsMonitor OptionsMonitor { get; } + private EventBus Events { get; } + + private async Task HandleEvent(Event data) + { + await Task.Yield(); + + Log.Debug("Handling event {Event}", data); + + bool EqualsThisEvent(string type) => type.Equals(data.Type.ToString(), StringComparison.OrdinalIgnoreCase); + bool EqualsLiterallyAnyEvent(string type) => type.Equals(EventType.Any.ToString(), StringComparison.OrdinalIgnoreCase); + + var options = OptionsMonitor.CurrentValue; + var webhooksTriggeredByThisEventType = options.Integration.Webhooks + .Where(kvp => kvp.Value.On.Any(EqualsThisEvent) || kvp.Value.On.Any(EqualsLiterallyAnyEvent)); + + foreach (var webhook in webhooksTriggeredByThisEventType) + { + Log.Information("{Webhook}", webhook); + } + } +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f18d9c09..b5af63a9 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -61,6 +61,7 @@ namespace slskd using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; using slskd.Integrations.Scripts; + using slskd.Integrations.Webhooks; using slskd.Messaging; using slskd.Relay; using slskd.Search; @@ -488,6 +489,7 @@ namespace slskd // hack: services that exist only to subscribe to the event bus are not referenced by anything else // and are thus never instantiated. force a reference here so they are created. _ = app.Services.GetService(); + _ = app.Services.GetService(); app.ConfigureAspDotNetPipeline(); @@ -583,6 +585,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); -- cgit v1.2.3 From 15ea17902dc57763912dbbab739a9891b112297a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:07:05 -0500 Subject: fix typo --- config/slskd.example.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index a7336d93..d589b23d 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -234,7 +234,7 @@ # my_logging_script: # on: # - All -# run: data/log_slskd_events.sh $EVENT +# run: data/log_slskd_events.sh $DATA # ftp: # enabled: false # address: ~ -- cgit v1.2.3 From f9ad53f89f255891a51ca442bb23c1d58ccf3bd0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:07:20 -0500 Subject: tweak webhook config --- config/slskd.example.yml | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index d589b23d..be2a0c6e 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -218,13 +218,18 @@ # on: # - DownloadFileComplete # call: -# url: http://192.168.1.42:8080/slskd_webhook +# url: https://192.168.1.42:8080/slskd_webhook # headers: -# - name: x-api-key +# - name: X-API-Key # value: foobar1234 -# - name: user-agent -# value: slskd/1.0 -# ignore_certificate_errors: true +# - name: Authorization +# value: Bearer eyJ...ssw5c +# - name: User-Agent +# value: slskd/0.0 +# ignore_certificate_errors: false +# timeout: 5000 # in milliseconds +# retry: +# attempts: 3 # scripts: # my_post_download_script: # on: -- cgit v1.2.3 From c907e234a98c9754e77adfefaf85d97021d0ece9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:07:55 -0500 Subject: don't log exceptions when the task doesn't throw --- src/slskd/Events/EventBus.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index 16b7c9e1..e1515ac3 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -103,7 +103,8 @@ public class EventBus // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => Task.Run(() => (subscriber.Value as Func)(data)) - .ContinueWith(task => Log.Error(task.Exception, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message)))); + .ContinueWith( + task => Log.Error(task.Exception, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message), TaskContinuationOptions.OnlyOnFaulted))); } } -- cgit v1.2.3 From 308a0afd86318b86d3ca1e88260c17de627bef11 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:08:11 -0500 Subject: add loopback endpoint --- src/slskd/Core/API/Controllers/ApplicationController.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index 790b6b3d..be646ae7 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -26,6 +26,7 @@ namespace slskd.Core.API using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; + using Serilog; /// /// Application. @@ -53,6 +54,7 @@ namespace slskd.Core.API private IStateMonitor ApplicationStateMonitor { get; } private IOptionsMonitor OptionsMonitor { get; } private IHostApplicationLifetime Lifetime { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Gets the current state of the application. @@ -149,5 +151,13 @@ namespace slskd.Core.API return PhysicalFile(file, "application/octet-stream", "slskd.dmp"); } + + [HttpPost("loopback")] + [Authorize(Policy = AuthPolicy.Any)] + public IActionResult Loopback([FromBody] object body) + { + Log.Information("Loopback POST: {Body}", body); + return Ok(); + } } -} +} \ No newline at end of file -- cgit v1.2.3 From 28e7090da1ec2a3711f660263edf37f78506a68b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:08:36 -0500 Subject: add timeout and retry options for webhooks --- src/slskd/Core/Options.cs | 44 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index a9d6aeb8..e5f16b1e 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2044,13 +2044,25 @@ namespace slskd /// Gets details about the webhook call. /// [Validate] - public WebhookDetails Call { get; init; } = new WebhookDetails(); + public WebhookHttpOptions Call { get; init; } = new WebhookHttpOptions(); + + /// + /// Gets the time to wait before timing out, in milliseconds. + /// + [Range(500, int.MaxValue)] + public int Timeout { get; init; } = 5000; + + /// + /// Gets the retry configuration. + /// + [Validate] + public RetryOptions Retry { get; init; } = new RetryOptions(); } /// - /// Webhook details. + /// Webhook HTTP options. /// - public class WebhookDetails : IValidatableObject + public class WebhookHttpOptions : IValidatableObject { /// /// Gets the fully qualified URL for the webhook. @@ -2062,7 +2074,7 @@ namespace slskd /// Gets the HTTP headers to include with the webhook. /// [Validate] - public WebhookDetailHeader[] Headers { get; init; } = []; + public WebhookHttpHeader[] Headers { get; init; } = []; /// /// Gets a value indicating whether HTTPS certificate errors should be ignored. @@ -2082,13 +2094,35 @@ namespace slskd } } - public class WebhookDetailHeader + /// + /// Webhook HTTP header configuration. + /// + public class WebhookHttpHeader { + /// + /// Gets the name of the header. + /// [NotNullOrWhiteSpace] public string Name { get; init; } + + /// + /// Gets the header's value. + /// public string Value { get; init; } } + /// + /// Retry configuration. + /// + public class RetryOptions + { + /// + /// Gets the number of attempts to make before failing. + /// + [Range(1, int.MaxValue)] + public int Attempts { get; init; } = 1; + } + /// /// Script configuration. /// -- cgit v1.2.3 From 746b2e6b2bd3f989319551e7b904f24243cf39c2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:08:57 -0500 Subject: fix bug that would prevent pushbullet failures from being reported --- src/slskd/Integrations/Pushbullet/PushbulletService.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index 5328f4d6..29033381 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -145,9 +145,13 @@ namespace slskd.Integrations.Pushbullet Log.LogDebug("Sending Pushbullet notification {Title} {Body}", title, body); await Retry.Do( - task: () => http.PostAsync(PushUri, content), + task: async () => + { + using var response = await http.PostAsync(PushUri, content); + response.EnsureSuccessStatusCode(); + }, isRetryable: (attempts, ex) => true, - onFailure: (attempts, ex) => Log.LogWarning("Failed attempt {Attempts} to send Pushbullet notification {Title} {Body}: {Message}", attempts, title, body, ex.Message), + onFailure: (attempts, ex) => Log.LogWarning("Failed attempt #{Attempts} to send Pushbullet notification {Title} {Body}: {Message}", attempts, title, body, ex.Message), maxAttempts: PushbulletOptions.RetryAttempts, maxDelayInMilliseconds: 30000); -- cgit v1.2.3 From 800c6436cc435ed7efde7eedb3087b08aa2df14d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:09:14 -0500 Subject: include event name when logging script errors --- src/slskd/Integrations/Scripts/ScriptService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 48916b2d..227f2fb1 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -120,7 +120,7 @@ public class ScriptService } catch (Exception ex) { - Log.Warning(ex, "Failed to run script '{Script}': {Message}", script.Key, ex.Message); + Log.Warning(ex, "Failed to run script '{Script}' for event type {Event}: {Message}", script.Key, data.Type, ex.Message); } finally { @@ -130,7 +130,7 @@ public class ScriptService } catch (Exception ex) { - Log.Warning(ex, "Failed to clean up process started from script '{Script}': {Message}", script.Key, ex.Message); + Log.Warning(ex, "Failed to clean up process started from script '{Script}' for event type {Event}: {Message}", script.Key, data.Type, ex.Message); } } }); -- cgit v1.2.3 From 8dea12b0097d9bec4f1a44c6e373dce6086b1d77 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:20:03 -0500 Subject: implement webhooks --- src/slskd/Integrations/Webhooks/WebhookService.cs | 62 +++++++++++++++++++++-- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/src/slskd/Integrations/Webhooks/WebhookService.cs b/src/slskd/Integrations/Webhooks/WebhookService.cs index 9ed0c947..768bf563 100644 --- a/src/slskd/Integrations/Webhooks/WebhookService.cs +++ b/src/slskd/Integrations/Webhooks/WebhookService.cs @@ -20,27 +20,36 @@ using Microsoft.Extensions.Options; namespace slskd.Integrations.Webhooks; using System; +using System.Diagnostics; using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using Serilog; using slskd.Events; public class WebhookService { - public WebhookService(EventBus eventBus, IOptionsMonitor optionsMonitor) + public WebhookService( + EventBus eventBus, + IOptionsMonitor optionsMonitor, + [FromKeyedServices(key: nameof(WebhookService))] IHttpClientFactory httpClientFactory) { Events = eventBus; OptionsMonitor = optionsMonitor; + HttpClientFactory = httpClientFactory; Events.Subscribe(nameof(WebhookService), HandleEvent); Log.Debug("{Service} initialized", nameof(WebhookService)); - Log.Warning("Webhook config: {Config}", OptionsMonitor.CurrentValue.Integration.Webhooks.ToJson()); } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private EventBus Events { get; } + private IHttpClientFactory HttpClientFactory { get; } private async Task HandleEvent(Event data) { @@ -57,7 +66,54 @@ public class WebhookService foreach (var webhook in webhooksTriggeredByThisEventType) { - Log.Information("{Webhook}", webhook); + _ = Task.Run(async () => + { + var call = webhook.Value.Call; + using var http = HttpClientFactory.CreateClient(); + http.Timeout = TimeSpan.FromMilliseconds(webhook.Value.Timeout); + + foreach (var header in call.Headers) + { + http.DefaultRequestHeaders.TryAddWithoutValidation(header.Name, header.Value); + } + + var content = new StringContent(data.ToJson(), Encoding.UTF8, "application/json"); + + HttpStatusCode? statusCode = null; + + try + { + Log.Debug("Calling webhook '{Name}': {Url}", webhook.Key, webhook.Value.Call.Url); + + var sw = Stopwatch.StartNew(); + + await Retry.Do( + task: async () => + { + using var response = await http.PostAsync(call.Url, content); + response.EnsureSuccessStatusCode(); + statusCode = response.StatusCode; + }, + isRetryable: (attempts, ex) => true, // retry everything + onFailure: (attempts, ex) => + { + if (webhook.Value.Retry.Attempts > 1) + { + Log.Warning(ex, "Failed attempt #{Attempts} to send webhook '{Name}' for event type {Event}: {Message}", attempts, webhook.Key, data.Type, ex.Message); + } + }, + maxAttempts: webhook.Value.Retry.Attempts, + maxDelayInMilliseconds: 30000); + + sw.Stop(); + + Log.Debug("Webhook '{Name}' called successfully in {Duration}ms; status code: {StatusCode}", webhook.Key, sw.ElapsedMilliseconds, statusCode); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to call webhook '{Name}' for event type {Event} after exhausting retries: {Message}", webhook.Key, data.Type, ex.Message); + } + }); } } } \ No newline at end of file -- cgit v1.2.3 From 8b8600be763119db7f79ff6d0e734b54fd24dafd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:21:24 -0500 Subject: remove keyed service --- src/slskd/Integrations/Webhooks/WebhookService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/slskd/Integrations/Webhooks/WebhookService.cs b/src/slskd/Integrations/Webhooks/WebhookService.cs index 768bf563..08dfd593 100644 --- a/src/slskd/Integrations/Webhooks/WebhookService.cs +++ b/src/slskd/Integrations/Webhooks/WebhookService.cs @@ -26,7 +26,6 @@ using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using Serilog; using slskd.Events; @@ -35,7 +34,7 @@ public class WebhookService public WebhookService( EventBus eventBus, IOptionsMonitor optionsMonitor, - [FromKeyedServices(key: nameof(WebhookService))] IHttpClientFactory httpClientFactory) + IHttpClientFactory httpClientFactory) { Events = eventBus; OptionsMonitor = optionsMonitor; -- cgit v1.2.3 From 600a15aaa031146378a127dcf60c596747a545a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 Nov 2024 20:36:56 -0500 Subject: tweak continuation options --- src/slskd/Events/EventBus.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index e1515ac3..ae3350f0 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -88,7 +88,9 @@ public class EventBus // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => Task.Run(() => (subscriber.Value as Func)(data)) - .ContinueWith(task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message)))); + .ContinueWith( + task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message), + continuationOptions: TaskContinuationOptions.OnlyOnFaulted))); } else { @@ -104,7 +106,8 @@ public class EventBus _ = Task.WhenAll(subscribers.Select(subscriber => Task.Run(() => (subscriber.Value as Func)(data)) .ContinueWith( - task => Log.Error(task.Exception, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message), TaskContinuationOptions.OnlyOnFaulted))); + task => Log.Error(task.Exception, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message), + continuationOptions: TaskContinuationOptions.OnlyOnFaulted))); } } -- cgit v1.2.3 From d6c7f53c92eb80ae2b491504c36d15e7a54ca297 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 Nov 2024 15:31:45 -0600 Subject: add note about UseExceptionHandler --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b5af63a9..3ded2e6b 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -839,6 +839,7 @@ namespace slskd private static WebApplication ConfigureAspDotNetPipeline(this WebApplication app) { + // stop ASP.NET from sending a full stack trace and ProblemDetails for unhandled exceptions app.UseExceptionHandler(a => a.Run(async context => { await context.Response.WriteAsJsonAsync(context.Features.Get().Error.Message); -- cgit v1.2.3 From 4ada795444443fff7b62d7d75404e6a835f18ec0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 Nov 2024 15:32:45 -0600 Subject: improve GetEvents --- src/slskd/Events/API/EventsController.cs | 33 ++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs index e9780fad..46afa5c7 100644 --- a/src/slskd/Events/API/EventsController.cs +++ b/src/slskd/Events/API/EventsController.cs @@ -17,6 +17,8 @@ namespace slskd.Events.API; +using System; +using System.Collections.Generic; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -42,13 +44,24 @@ public class EventsController : ControllerBase private EventService Events { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - [HttpGet("")] + /// + /// Retrieves a paginated list of past records. + /// + /// The offset (number of records) at which to start the requested page. + /// The page size. + /// The list of records. + [HttpGet("", Name = nameof(GetEvents))] [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(string), 400)] + [ProducesResponseType(401)] + [ProducesResponseType(403)] + [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(typeof(string), 500)] public IActionResult GetEvents([FromQuery] int offset = 0, [FromQuery] int limit = 100) { if (offset < 0) { - return BadRequest("Offset must be greater than or equal to zero."); + return BadRequest("Offset must be greater than or equal to zero"); } if (limit <= 0) @@ -56,11 +69,19 @@ public class EventsController : ControllerBase return BadRequest("Limit must be greater than zero"); } - var events = Events.Get(offset, limit); - var count = Events.Count(); + try + { + var eventRecords = Events.Get(offset, limit); + var count = Events.Count(); - Response.Headers.Append("X-Total-Count", count.ToString()); + Response.Headers.Append("X-Total-Count", count.ToString()); - return Ok(events); + return Ok(eventRecords); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list events: {Message}", ex.Message); + throw; + } } } \ No newline at end of file -- cgit v1.2.3 From 4d5c0e437065e104a784b7080915ca2bfdd2218c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 Nov 2024 16:47:29 -0600 Subject: add an IHttpClientFactory with SSL disabled --- src/slskd/Core/Constants.cs | 23 +++++++++++++++++++++++ src/slskd/Program.cs | 10 ++++++++++ 2 files changed, 33 insertions(+) create mode 100644 src/slskd/Core/Constants.cs diff --git a/src/slskd/Core/Constants.cs b/src/slskd/Core/Constants.cs new file mode 100644 index 00000000..380a3519 --- /dev/null +++ b/src/slskd/Core/Constants.cs @@ -0,0 +1,23 @@ +// +// 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/. +// + +namespace slskd; + +public static class Constants +{ + public static readonly string IgnoreCertificateErrors = nameof(IgnoreCertificateErrors); +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 3ded2e6b..1ac798c1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -26,6 +26,7 @@ namespace slskd using System.IO; using System.Linq; using System.Net; + using System.Net.Http; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; @@ -546,6 +547,15 @@ namespace slskd // this is important to prevent memory leaks services.AddHttpClient(); + // add a special HttpClientFactory to DI that disables SSL. access it via: + // 'using var http = HttpClientFactory.CreateClient(Constants.IgnoreCertificateErrors)' + // thanks Microsoft, makes total sense and surely won't be easy to fuck up later! + services.AddHttpClient(Constants.IgnoreCertificateErrors) + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler + { + ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, + }); + // add a partially configured instance of SoulseekClient. the Application instance will // complete configuration at startup. services.AddSingleton(_ => -- cgit v1.2.3 From ca38ca6286da1c8bb8185f7678ef7fe884ae1f07 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 Nov 2024 16:48:14 -0600 Subject: use the ssl-disabled httpclientfactory if option is set --- src/slskd/Integrations/Webhooks/WebhookService.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/slskd/Integrations/Webhooks/WebhookService.cs b/src/slskd/Integrations/Webhooks/WebhookService.cs index 08dfd593..62f097b7 100644 --- a/src/slskd/Integrations/Webhooks/WebhookService.cs +++ b/src/slskd/Integrations/Webhooks/WebhookService.cs @@ -68,7 +68,11 @@ public class WebhookService _ = Task.Run(async () => { var call = webhook.Value.Call; - using var http = HttpClientFactory.CreateClient(); + + using var http = call.IgnoreCertificateErrors + ? HttpClientFactory.CreateClient(Constants.IgnoreCertificateErrors) + : HttpClientFactory.CreateClient(); + http.Timeout = TimeSpan.FromMilliseconds(webhook.Value.Timeout); foreach (var header in call.Headers) -- cgit v1.2.3 From 7f9a694da61bb046343d9f98ec2b5cd8b444e56b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 Nov 2024 16:48:24 -0600 Subject: add webhook docs --- docs/config.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/docs/config.md b/docs/config.md index 6717dd5c..e10fcbbe 100644 --- a/docs/config.md +++ b/docs/config.md @@ -922,6 +922,41 @@ retention: # Integrations +## Webhooks + +Webhooks (outbound HTTP requests) can be configured to be called when application events are raised. Webhooks are given a name (useful for troubleshooting!), a list of triggering events, a `call` configuration that defines the HTTP request to be made, and timeout and retry configuration. + +Webhook HTTP requests are always a `POST`, and will always include the event data in the body, serialized as JSON. Users define a fully-qualified endpoint address, an optional collection of headers, and an optional flag to ignore HTTPS errors caused by invalid (e.g. self signed) certificates. + +If unconfigured, the default timeout for requests is 5 seconds, and each request will be attempted only once per event. + +#### **YAML** +```yaml +integration: + webhooks: + my_basic_webhook_using_defaults: + on: + - All + call: + url: http://localhost:4224 + my_webhook_using_detailed_config: + on: + - DownloadFileComplete + call: + url: https://192.168.1.42:8080/slskd_webhook + headers: + - name: X-API-Key # if using API key style authentication + value: foobar1234 + - name: Authorization # if using JWT authentication + value: Bearer eyJ...ssw5c + - name: User-Agent # can be useful! + value: slskd/0.0 + ignore_certificate_errors: true # defaults to false + timeout: 5000 # in milliseconds + retry: + attempts: 3 +``` + ## User-Defined Scripts User-defined scripts can be configured to run when application events are raised. Scripts are given a name (useful for troubleshooting!), a list of triggering events, and a `run` command that's used to execute the script. -- cgit v1.2.3