From 81c548029ebed89407c055d62ebec6a503bcdde6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Oct 2022 18:18:55 -0500 Subject: improve stream lifecycle handling --- src/slskd/Network/API/Hubs/NetworkHub.cs | 7 +-- src/slskd/Network/NetworkService.cs | 100 +++++++++++++++++++++---------- 2 files changed, 71 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 28a6b0f7..7945a62b 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -95,12 +95,9 @@ namespace slskd.Network throw new UnauthorizedAccessException(); } - public void NotifyUploadFailed(Guid id) + public void NotifyUploadFailed(Guid id, Exception exception) { - if (Network.PendingFileUploads.TryGetValue(id, out var record)) - { - record.Stream.TrySetException(new NotFoundException("The file could not be uploaded from the remote agent")); - } + Network.NotifyFileStreamFailure(id, exception); } public void ReturnFileInfo(Guid id, bool exists, long length) diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 792be99c..7a56eb1c 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -32,11 +32,6 @@ namespace slskd.Network public interface INetworkService { - /// - /// Gets the collection of pending Agent file uploads. - /// - ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } - /// /// Gets the name of the local host. /// @@ -68,9 +63,24 @@ namespace slskd.Network /// /// The agent from which to retrieve the file. /// The file to retrieve. + /// A unique ID for the stream. /// An optional timeout value. /// The operation context, including a stream containing the requested file. - Task GetFileStream(string agentName, string filename, int timeout = 3000); + Task GetFileStream(string agentName, string filename, Guid id, int timeout = 3000); + + /// + /// Safely attempts to close a stream obtained with . + /// + /// The unique ID for the stream. + /// If the transfer associated with the stream failed, the exception that caused the failure. + void TryCloseFileStream(Guid id, Exception exception = null); + + /// + /// Notifies the caller of of a failure to obtain a file stream from the requested agent. + /// + /// The unique ID for the stream. + /// The remote exception that caused the failure. + void NotifyFileStreamFailure(Guid id, Exception exception); /// /// Retrieves information about the specified from the specified . @@ -89,7 +99,13 @@ namespace slskd.Network /// The client response to the request. void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); - Task HandleGetFileStreamResponse(string agentName, string filename, Guid id, Stream response); + /// + /// Handles the client response for a request, returning when the corresponding file upload is complete. + /// + /// The ID of the request. + /// The client response to the request. + /// The operation context. + Task HandleGetFileStreamResponse(Guid id, Stream response); void HandleGetFileStreamCompletion(string agentName, string filename); @@ -158,11 +174,6 @@ namespace slskd.Network OptionsMonitor = optionsMonitor; } - /// - /// Gets the collection of pending Agent uploads. - /// - public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); - /// /// Gets the collection of registered Agents. /// @@ -178,7 +189,7 @@ namespace slskd.Network private IHubContext NetworkHub { get; set; } private IOptionsMonitor OptionsMonitor { get; } private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); - private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary WaitIdDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); private IWaiter Waiter { get; } @@ -219,35 +230,35 @@ namespace slskd.Network /// /// The agent from which to retrieve the file. /// The file to retrieve. + /// A unique ID for the stream. /// An optional timeout value. /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - public async Task GetFileStream(string agentName, string filename, int timeout = 3000) + public async Task GetFileStream(string agentName, string filename, Guid id, int timeout = 3000) { if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { throw new NotFoundException($"Agent {agentName} is not registered"); } - var token = Guid.NewGuid(); // cache the id to prevent replay attacks; the agent should respond within the timeout, otherwise // when it does we will no longer know about it - MemoryCache.Set(GetFileTokenCacheKey(filename, token), agentName, TimeSpan.FromMilliseconds(timeout)); - Log.Debug("Cached file upload token {Token} for agent {Agent}", token, agentName); - - await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, token); - Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agentName, token); + MemoryCache.Set(GetFileTokenCacheKey(filename, id), agentName, TimeSpan.FromMilliseconds(timeout)); + Log.Debug("Cached file upload token {Token} for agent {Agent}", id, agentName); // create a wait for the agent response. this wait will be completed in the response handler, // ultimately called from the API controller when the agent makes an HTTP request to return the file - var key = new WaitKey(nameof(GetFileStream), agentName, filename, token); + var key = new WaitKey(nameof(GetFileStream), id); var wait = Waiter.Wait(key, timeout); + await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, id); + Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agentName, id); + var task = await Task.WhenAny(wait, Task.Delay(timeout)); if (task == wait) { // send the stream back to the caller so it can be used to feed data to the remote client - Log.Information("Agent {Agent} provided file stream for file {Filename} with ID {Id}", agentName, filename, token); + Log.Information("Agent {Agent} provided file stream for file {Filename} with ID {Id}", agentName, filename, id); var stream = await wait; return stream; } @@ -257,6 +268,35 @@ namespace slskd.Network } } + /// + /// Notifies the caller of of a failure to obtain a file stream from the requested agent. + /// + /// The unique ID for the stream. + /// The remote exception that caused the failure. + public void NotifyFileStreamFailure(Guid id, Exception exception) + { + var key = new WaitKey(nameof(GetFileStream), id); + Waiter.Throw(key, exception); + } + + /// + /// Safely attempts to close a stream obtained with . + /// + /// The unique ID for the stream. + /// If the transfer associated with the stream failed, the exception that caused the failure. + public void TryCloseFileStream(Guid id, Exception exception = default) + { + var key = new WaitKey(nameof(HandleGetFileStreamResponse), id); + + if (exception != default) + { + Waiter.Throw(key, exception); + return; + } + + Waiter.Complete(key); + } + /// /// Retrieves information about the specified from the specified . /// @@ -299,7 +339,7 @@ namespace slskd.Network { var key = new WaitKey(nameof(GetFileInfo), agentName, id); - if (!Waiter.ContainsKey(key)) + if (!Waiter.IsWaitingFor(key)) { Log.Warning("Agent {Agent} responded to a file info request with Id {Id}, but a response was not expected", agentName, id); return; @@ -312,33 +352,31 @@ namespace slskd.Network /// /// Handles the client response for a request, returning when the corresponding file upload is complete. /// - /// The agent that provided the response. - /// The name of the file. /// The ID of the request. /// The client response to the request. /// The operation context. - public async Task HandleGetFileStreamResponse(string agentName, string filename, Guid id, Stream response) + public async Task HandleGetFileStreamResponse(Guid id, Stream response) { - var streamKey = new WaitKey(nameof(GetFileStream), agentName, filename, id); + var streamKey = new WaitKey(nameof(GetFileStream), id); - if (!Waiter.ContainsKey(streamKey)) + if (!Waiter.IsWaitingFor(streamKey)) { - Log.Warning("Agent {Agent} responded to a file request with Id {Id}, but a response was not expected", agentName, id); + Log.Warning("A file stream response matching Id {Id} is not expected", id); return; } // 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(GetFileStream), "completion", agentName, filename); + var completionKey = new WaitKey(nameof(HandleGetFileStreamResponse), 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 sends execution back to the body of GetFileStream and the upload will begin transferring data Waiter.Complete(streamKey, response); - Log.Information("Agent {Agent} responded to a file request with Id {Id}", agentName, id); // wait for the caller of GetFileStream to report that the upload/stream is complete + // this is the wait that keeps the HTTP handler running await completion; } -- cgit v1.2.3