From 653c05040acab0f7aff9a98cd959a0c54e05e300 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Oct 2022 18:28:43 -0500 Subject: refactor handling of streams --- src/slskd/Network/NetworkService.cs | 196 ++++++++++++++++++++---------------- 1 file changed, 108 insertions(+), 88 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 845c284e..747602fd 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -58,6 +58,15 @@ namespace slskd.Network /// The generated token. Guid GenerateShareUploadToken(string agentName); + /// + /// Retrieves a stream of the specified from the specified . + /// + /// The agent from which to retrieve the file. + /// The file to retrieve. + /// An optional timeout value. + /// The operation context, including a stream containing the requested file. + Task GetFileStream(string agentName, string filename, int timeout = 3000); + /// /// Retrieves information about the specified from the specified . /// @@ -68,13 +77,16 @@ namespace slskd.Network Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000); /// - /// Retrieves a stream of the specified from the specified . + /// Handles the client response for a request. /// - /// The agent from which to retrieve the file. - /// The file to retrieve. - /// An optional timeout value. - /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - Task<(Stream Stream, TaskCompletionSource Completion)> GetFile(string agentName, string filename, int timeout = 3000); + /// The agent that provided the response. + /// The ID of the request. + /// 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); + + void HandleGetFileStreamCompletion(string agentName, string filename); /// /// Registers the specified with the specified . @@ -83,14 +95,6 @@ namespace slskd.Network /// The agent. void RegisterAgent(string connectionId, Agent agent); - /// - /// Handles the client response for a request. - /// - /// The agent that provided the response. - /// The ID of the request. - /// The client response to the request. - void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); - /// /// Attempts to remove the registration for the specified . /// @@ -117,23 +121,23 @@ namespace slskd.Network bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse); /// - /// Attempts to validate the share upload response credential associated with the specified . + /// Attempts to validate the file upload response credential associated with the specified . /// /// The token. /// The name of the responding agent. + /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - bool TryValidateShareUploadCredential(Guid token, string agentName, string credential); + bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential); /// - /// Attempts to validate the file upload response credential associated with the specified . + /// Attempts to validate the share upload response credential associated with the specified . /// /// The token. /// The name of the responding agent. - /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential); + bool TryValidateShareUploadCredential(Guid token, string agentName, string credential); } public class NetworkService : INetworkService @@ -159,7 +163,6 @@ namespace slskd.Network /// public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); - private IWaiter Waiter { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IHubContext NetworkHub { get; set; } @@ -167,6 +170,7 @@ namespace slskd.Network private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private IWaiter Waiter { get; } /// /// Generates a random authentication challenge token for the specified . @@ -200,6 +204,48 @@ namespace slskd.Network return token; } + /// + /// Retrieves a stream of the specified from the specified . + /// + /// The agent from which to retrieve the file. + /// The file to retrieve. + /// 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) + { + 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); + + // 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 wait = Waiter.Wait(key, timeout); + + 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 + var stream = await wait; + return stream; + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agentName}"); + } + } + /// /// Retrieves information about the specified from the specified . /// @@ -253,72 +299,45 @@ namespace slskd.Network } /// - /// Retrieves a stream of the specified from the specified . + /// Handles the client response for a request, returning when the corresponding file upload is complete. /// - /// The agent from which to retrieve the file. - /// The file to retrieve. - /// An optional timeout value. - /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFile(string agentName, string filename, int timeout = 3000) + /// 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) { - if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) + var streamKey = new WaitKey(nameof(GetFileStream), agentName, filename, id); + + if (!Waiter.ContainsKey(streamKey)) { - throw new NotFoundException($"Agent {agentName} is not registered"); + Log.Warning("Agent {Agent} responded to a file request with Id {Id}, but a response was not expected", agentName, id); + return; } - var token = Guid.NewGuid(); - var key = new WaitKey(nameof(GetFile), agentName, token); - var wait = Waiter.Wait(key, timeout); - - MemoryCache.Set(GetFileTokenCacheKey(filename, token), agentName, TimeSpan.FromMinutes(1)); - Log.Debug("Cached file upload token {Token} for agent {Agent}", token, agentName); - - // create a TCS for the upload stream. this is awaited below and completed in the API controller when the agent POSTs - // the file - var upload = new TaskCompletionSource(); + // 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 completion = Waiter.WaitIndefinitely(completionKey); - // create a TCS for the upload itself. this is awaited by the API controller and completed by the transfer service - // when the upload to the remote user is complete the API controller needs to wait until the remote transfer is - // complete in order to keep the stream open for the duration - var completion = new TaskCompletionSource(); - - PendingFileUploadDictionary.TryAdd(token, (upload, completion)); - - try - { - 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); - - var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); + // 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); - if (task == upload.Task) - { - var stream = await upload.Task; - return (stream, completion); - } - else - { - throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agentName}"); - } - } - finally - { - PendingFileUploadDictionary.TryRemove(token, out _); - } + // wait for the caller of GetFileStream to report that the upload/stream is complete + await completion; } - public void HandleGetFileResponse(string agentName, Guid id, Stream response) + public void HandleGetFileStreamCompletion(string agentName, string filename) { - var key = new WaitKey(nameof(GetFile), agentName, id); - - if (!Waiter.ContainsKey(key)) - { - Log.Warning("Agent {Agent} responded to a file request with Id {Id}, but a response was not expected", agentName, id); - return; - } - - Waiter.Complete(key, response); - Log.Information("Agent {Agent} responded to a file request with Id {Id}", agentName, id); + // complete the indefinite wait for this upload. this sends execution back to the body of the file + // stream response handler, and ultimately back to the API controller. the agent's original HTTP request + // will complete. + var key = new WaitKey(nameof(GetFileStream), "completion", agentName, filename); + Waiter.Complete(key); } /// @@ -389,30 +408,36 @@ namespace slskd.Network } /// - /// Attempts to validate the share upload response credential associated with the specified . + /// Attempts to validate the file upload response credential associated with the specified . /// /// The token. /// The name of the responding agent. + /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - public bool TryValidateShareUploadCredential(Guid token, string agentName, string credential) + public bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential) { - return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); + return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(filename, token)); } /// - /// Attempts to validate the file upload response credential associated with the specified . + /// Attempts to validate the share upload response credential associated with the specified . /// /// The token. /// The name of the responding agent. - /// The name of the file being uploaded. /// The response credential. /// A value indicating whether the credential is valid. - public bool TryValidateFileUploadCredential(Guid token, string agentName, string filename, string credential) + public bool TryValidateShareUploadCredential(Guid token, string agentName, string credential) { - return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(filename, token)); + return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); } + private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; + + private string GetFileTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.file"; + + private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; + private bool TryValidateCredential(string token, string agentName, string credential, string cacheKey) { try @@ -459,10 +484,5 @@ namespace slskd.Network MemoryCache.Remove(cacheKey); } } - - private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; - - private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; - private string GetFileTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.file"; } } \ No newline at end of file -- cgit v1.2.3