From a5ca9a6c0397370ac2ea6b79be1641b9e64a4336 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 20 Jan 2023 16:15:44 -0600 Subject: docs, add controller connect/disconnect to route --- src/slskd/Relay/API/Controllers/RelayController.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'src/slskd/Relay/API/Controllers/RelayController.cs') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index f6c6d778..e3c3d28b 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -41,6 +41,12 @@ namespace slskd.Relay [ApiController] public class RelayController : ControllerBase { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// public RelayController( IRelayService relayService, IOptionsMonitor optionsMonitor, @@ -57,7 +63,11 @@ namespace slskd.Relay private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum(); private IOptionsMonitor OptionsMonitor { get; } - [HttpPut("")] + /// + /// Connects to the configured controller. + /// + /// + [HttpPut("controller")] [Authorize(Policy = AuthPolicy.JwtOnly)] public async Task Connect() { @@ -70,7 +80,11 @@ namespace slskd.Relay return Ok(); } - [HttpDelete("")] + /// + /// Disconnects from the connected controller. + /// + /// + [HttpDelete("controller")] [Authorize(Policy = AuthPolicy.JwtOnly)] public async Task Disconnect() { -- cgit v1.2.3 From 2f1d36d46836f90bac27bb8dd957a15ba7b6429b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 20 Jan 2023 16:17:18 -0600 Subject: separate agent and controller actions by route --- src/slskd/Relay/API/Controllers/RelayController.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src/slskd/Relay/API/Controllers/RelayController.cs') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index e3c3d28b..f76e8288 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -67,7 +67,7 @@ namespace slskd.Relay /// Connects to the configured controller. /// /// - [HttpPut("controller")] + [HttpPut("agent")] [Authorize(Policy = AuthPolicy.JwtOnly)] public async Task Connect() { @@ -84,7 +84,7 @@ namespace slskd.Relay /// Disconnects from the connected controller. /// /// - [HttpDelete("controller")] + [HttpDelete("agent")] [Authorize(Policy = AuthPolicy.JwtOnly)] public async Task Disconnect() { @@ -102,7 +102,7 @@ namespace slskd.Relay /// /// The unique identifier for the request. /// - [HttpGet("downloads/{token}")] + [HttpGet("controller/downloads/{token}")] [Authorize(Policy = AuthPolicy.ApiKeyOnly)] public IActionResult DownloadFile([FromRoute]string token) { @@ -153,7 +153,7 @@ namespace slskd.Relay /// /// The unique identifier for the request. /// - [HttpPost("files/{token}")] + [HttpPost("controller/files/{token}")] [RequestSizeLimit(10L * 1024L * 1024L * 1024L)] [RequestFormLimits(MultipartBodyLengthLimit = 10L * 1024L * 1024L * 1024L)] [DisableFormValueModelBinding] @@ -251,7 +251,7 @@ namespace slskd.Relay /// /// The unique identifier for the request. /// - [HttpPost("shares/{token}")] + [HttpPost("controller/shares/{token}")] [Authorize(Policy = AuthPolicy.ApiKeyOnly)] public async Task UploadShares(string token) { -- cgit v1.2.3 From 3b4f9e74ae0032f1f54c53f4fb5e39abd34db106 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 21 Jan 2023 11:19:50 -0600 Subject: docs --- src/slskd/Relay/API/Controllers/RelayController.cs | 6 +++--- src/slskd/Relay/API/Hubs/RelayHub.cs | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src/slskd/Relay/API/Controllers/RelayController.cs') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index f76e8288..ee282b17 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -98,7 +98,7 @@ namespace slskd.Relay } /// - /// Downloads a file. + /// Downloads a file from the connected controller. /// /// The unique identifier for the request. /// @@ -149,7 +149,7 @@ namespace slskd.Relay } /// - /// Uploads a file. + /// Uploads a file to the connected controller. /// /// The unique identifier for the request. /// @@ -247,7 +247,7 @@ namespace slskd.Relay } /// - /// Uploads share information. + /// Uploads share information to the connected controller. /// /// The unique identifier for the request. /// diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index 43f49976..e246711e 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -169,7 +169,7 @@ namespace slskd.Relay } /// - /// Initiates the share upload workflow by generating and retrieving a request token. + /// Executed by the agent to initiate the share upload workflow by generating and retrieving a request token. /// /// The generated token. /// Thrown when the agent is not fully authenticated. @@ -188,7 +188,7 @@ namespace slskd.Relay } /// - /// Notifies the controller that the agent was unable to upload the file requested by a call to . + /// Executed by the agent to notify the controller that the agent was unable to upload the file requested by a call to . /// /// The unique identifier of the request. /// The Exception that caused the failure. @@ -207,7 +207,7 @@ namespace slskd.Relay } /// - /// Returns the response to a call to . + /// Executed by the agent to return the response to a call to . /// /// The unique identifier for the request. /// A value indicating whether the requested file exists on the agent's filesystem. -- cgit v1.2.3 From 1340ffa52dd3aaa63840f9e36f3e6fb495d97a86 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 22 Jan 2023 22:19:06 -0600 Subject: polish RelayService --- src/slskd/Relay/API/Controllers/RelayController.cs | 4 +- src/slskd/Relay/RelayService.cs | 162 +++++++++++---------- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 3 files changed, 89 insertions(+), 79 deletions(-) (limited to 'src/slskd/Relay/API/Controllers/RelayController.cs') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index ee282b17..586cbbb2 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -235,7 +235,7 @@ namespace slskd.Relay // pass the stream back to the relay service, which will in turn pass it to the upload service, and use it to // feed data into the remote upload. await this call, it will complete when the upload is complete, one way or the other. - await Relay.HandleFileStreamResponse(agentName, id: guid, stream); + await Relay.HandleFileStreamResponseAsync(agentName, id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); return Ok(); @@ -321,7 +321,7 @@ namespace slskd.Relay Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)inputStream.Length).SizeSuffix(), sw.ElapsedMilliseconds); - await Relay.HandleShareUpload(agentName, id: guid, shares, temp); + await Relay.HandleShareUploadAsync(agentName, id: guid, shares, temp); return Ok(); } diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index c0044020..a403fa73 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -54,13 +54,6 @@ namespace slskd.Relay /// IStateMonitor StateMonitor { get; } - /// - /// Notifies connected agents that a file download has completed. - /// - /// The filename of the completed file, relative to the downloads directory. - /// The operation context. - Task BroadcastFileDownloadCompletedNotificationAsync(string filename); - /// /// Generates a random authentication challenge token for the specified . /// @@ -76,12 +69,13 @@ namespace slskd.Relay /// This is the first step in a multi-step workflow. The entire sequence is: /// /// - /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn - /// calls . The token is generated and cached, and is only valid while it is in the cache. + /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn calls + /// . The token is generated and cached, and is only valid while it is + /// in the cache. /// /// - /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its - /// shared database and a serialized list of locally configured shares, and the controller invokes . + /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its shared + /// database and a serialized list of locally configured shares, and the controller invokes . /// /// /// @@ -173,7 +167,7 @@ namespace slskd.Relay /// The ID of the request. /// The client response to the request. /// The operation context. - Task HandleFileStreamResponse(string agentName, Guid id, Stream response); + Task HandleFileStreamResponseAsync(string agentName, Guid id, Stream response); /// /// Handles incoming share uploads. @@ -183,7 +177,14 @@ namespace slskd.Relay /// The list of shares provided. /// The filename of the temporary file containing the upload. /// The operation context. - Task HandleShareUpload(string agentName, Guid id, IEnumerable shares, string filename); + Task HandleShareUploadAsync(string agentName, Guid id, IEnumerable shares, string filename); + + /// + /// Notifies connected agents that a file download has completed. + /// + /// The filename of the completed file, relative to the downloads directory. + /// The operation context. + Task NotifyFileDownloadCompleteAsync(string filename); /// /// Notifies the caller of of a failure to obtain a file stream from the requested agent. @@ -267,6 +268,16 @@ namespace slskd.Relay /// public class RelayService : IRelayService { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + /// + /// + /// public RelayService( IWaiter waiter, IShareService shareService, @@ -309,68 +320,20 @@ namespace slskd.Relay public IStateMonitor StateMonitor { get; } private IHttpClientFactory HttpClientFactory { get; } + private string LastControllerOptionsHash { get; set; } + private string LastOptionsHash { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); - private IHubContext RelayHub { get; set; } private IOptionsMonitor OptionsMonitor { get; } private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private IHubContext RelayHub { get; set; } private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareService Shares { get; } - private IWaiter Waiter { get; } private IManagedState State { get; } = new ManagedState(); - private ConcurrentDictionary WaitIdDictionary { get; } = new(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private string LastOptionsHash { get; set; } - private string LastControllerOptionsHash { get; set; } - - /// - /// Notifies connected agents that a file download has completed. - /// - /// The filename of the completed file, relative to the downloads directory. - /// The operation context. - public Task BroadcastFileDownloadCompletedNotificationAsync(string filename) - { - if (!OptionsMonitor.CurrentValue.Relay.Enabled || - !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OptionsMonitor.CurrentValue.Relay.Mode.ToEnum())) - { - return Task.CompletedTask; - } - - var agents = RegisteredAgentDictionary.Values; - - if (!agents.Any()) - { - return Task.CompletedTask; - } - - // ensure filename is relative to the local download directory - // and make sure it doesn't start with a slash - filename = filename - .ReplaceFirst(OptionsMonitor.CurrentValue.Directories.Downloads, string.Empty) - .TrimStart(new[] { '/', '\\' }); - - async Task Notify((string ConnectionId, Agent Agent) record) - { - try - { - var id = Guid.NewGuid(); - - MemoryCache.Set(GetDownloadTokenCacheKey(filename, id), record.Agent.Name, TimeSpan.FromMinutes(10)); - Log.Debug("Cached file download token {Token} for agent {Agent}", id, record.Agent.Name); - - await RelayHub.Clients.Client(record.ConnectionId).NotifyFileDownloadCompleted(filename, id); - } - catch - { - Log.Warning("Failed to notify agent {Agent} of download completion for {Filename}", record.Agent.Name, filename); - } - } - - Log.Information("Notifying agents of download completion for {Filename}", filename); - - return Task.WhenAll(RegisteredAgentDictionary.Values.Select(Notify)); - } + private IWaiter Waiter { get; } + private ConcurrentDictionary WaitIdDictionary { get; } = new(); /// /// Generates a random authentication challenge token for the specified . @@ -396,16 +359,16 @@ namespace slskd.Relay /// This is the first step in a multi-step workflow. The entire sequence is: /// /// - /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn - /// calls . The token is generated and cached. + /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn calls + /// . The token is generated and cached. /// /// - /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its - /// shared database and a serialized list of locally configured shares. + /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its shared + /// database and a serialized list of locally configured shares. /// /// - /// The HTTP controller saves the database backup to a temporary file, validates it, and then adds (or updates) - /// a share host for the agent. + /// The HTTP controller saves the database backup to a temporary file, validates it, and then adds (or + /// updates) a share host for the agent. /// /// /// @@ -582,7 +545,7 @@ namespace slskd.Relay /// The ID of the request. /// The client response to the request. /// The operation context. - public async Task HandleFileStreamResponse(string agentName, Guid id, Stream response) + public async Task HandleFileStreamResponseAsync(string agentName, Guid id, Stream response) { var streamKey = new WaitKey(nameof(GetFileStreamAsync), agentName, id); @@ -596,7 +559,7 @@ namespace slskd.Relay // create a wait (but do not await it) for the completion of the upload to the remote client. we need to await this to // keep execution in the body of the API controller that provided the stream, in order to keep the stream open for the // duration of the remote transfer. omit the id from the key, the caller doesn't know it. - var completionKey = new WaitKey(nameof(HandleFileStreamResponse), agentName, id); + var completionKey = new WaitKey(nameof(HandleFileStreamResponseAsync), agentName, id); var completion = Waiter.WaitIndefinitely(completionKey); // complete the wait that's waiting for the stream, so we can send the stream back to the caller of GetFileStream this @@ -616,7 +579,7 @@ namespace slskd.Relay /// The list of shares provided. /// The filename of the temporary file containing the upload. /// The operation context. - public Task HandleShareUpload(string agentName, Guid id, IEnumerable shares, string filename) + public Task HandleShareUploadAsync(string agentName, Guid id, IEnumerable shares, string filename) { Log.Information("Loading shares from agent {Agent}", agentName); @@ -638,6 +601,53 @@ namespace slskd.Relay return Task.CompletedTask; } + /// + /// Notifies connected agents that a file download has completed. + /// + /// The filename of the completed file, relative to the downloads directory. + /// The operation context. + public Task NotifyFileDownloadCompleteAsync(string filename) + { + if (!OptionsMonitor.CurrentValue.Relay.Enabled || + !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OptionsMonitor.CurrentValue.Relay.Mode.ToEnum())) + { + return Task.CompletedTask; + } + + var agents = RegisteredAgentDictionary.Values; + + if (!agents.Any()) + { + return Task.CompletedTask; + } + + // ensure filename is relative to the local download directory and make sure it doesn't start with a slash + filename = filename + .ReplaceFirst(OptionsMonitor.CurrentValue.Directories.Downloads, string.Empty) + .TrimStart(new[] { '/', '\\' }); + + async Task Notify((string ConnectionId, Agent Agent) record) + { + try + { + var id = Guid.NewGuid(); + + MemoryCache.Set(GetDownloadTokenCacheKey(filename, id), record.Agent.Name, TimeSpan.FromMinutes(10)); + Log.Debug("Cached file download token {Token} for agent {Agent}", id, record.Agent.Name); + + await RelayHub.Clients.Client(record.ConnectionId).NotifyFileDownloadCompleted(filename, id); + } + catch + { + Log.Warning("Failed to notify agent {Agent} of download completion for {Filename}", record.Agent.Name, filename); + } + } + + Log.Information("Notifying agents of download completion for {Filename}", filename); + + return Task.WhenAll(RegisteredAgentDictionary.Values.Select(Notify)); + } + /// /// Notifies the caller of of a failure to obtain a file stream from the requested agent. /// @@ -668,7 +678,7 @@ namespace slskd.Relay /// If the transfer associated with the stream failed, the exception that caused the failure. public void TryCloseFileStream(string agentName, Guid id, Exception exception = default) { - var key = new WaitKey(nameof(HandleFileStreamResponse), agentName, id); + var key = new WaitKey(nameof(HandleFileStreamResponseAsync), agentName, id); if (exception != default) { diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c85ff551..827a0528 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -232,7 +232,7 @@ namespace slskd.Transfers.Downloads if (OptionsMonitor.CurrentValue.Relay.Enabled) { - _ = Relay.BroadcastFileDownloadCompletedNotificationAsync(finalFilename); + _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); } if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) -- cgit v1.2.3