From 120c6d0631fbd9a9f2c262171e713fcc6df01ea2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 08:57:09 -0500 Subject: rename Agents namespace to Network --- .../Network/API/Controllers/NetworkController.cs | 83 ++++++++++++++++++++ src/slskd/Network/API/Hubs/NetworkHub.cs | 91 ++++++++++++++++++++++ 2 files changed, 174 insertions(+) create mode 100644 src/slskd/Network/API/Controllers/NetworkController.cs create mode 100644 src/slskd/Network/API/Hubs/NetworkHub.cs (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs new file mode 100644 index 00000000..836921f1 --- /dev/null +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -0,0 +1,83 @@ +// +// 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.Network +{ + using System; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Serilog; + + /// + /// Network. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + public class NetworkController : ControllerBase + { + public NetworkController(INetworkService networkService) + { + Network = networkService; + } + + private INetworkService Network { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Gets the current state of the application. + /// + /// + [HttpPost("files/{id}")] + [Authorize] + public async Task UploadFile(string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest("Id is not a valid Guid"); + } + + // get the record for the waiting file + if (Network.PendingUploads.TryGetValue(guid, out var record)) + { + // get the stream from the multipart upload + var stream = Request.Form.Files.First().OpenReadStream(); + + // set the result for the stream + // this should pass control to the transfer service along with + // the stream + record.Upload.SetResult(stream); + + Console.WriteLine("Stream handed off. Waiting for completion..."); + + // wait for the transfer service to set the completion result + await record.Completion.Task; + + stream.Dispose(); + Console.WriteLine("Upload complete"); + return Ok(); + } + else + { + Log.Warning("Agent"); + return NotFound(); + } + } + } +} diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs new file mode 100644 index 00000000..61ac08f0 --- /dev/null +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -0,0 +1,91 @@ +// +// 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.Network +{ + using System; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.SignalR; + using Serilog; + + public static class NetworkHubMethods + { + public static readonly string RequestFile = "REQUEST_FILE"; + public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; + public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; + public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; + } + + /// + /// Extension methods for the network SignalR hub. + /// + public static class NetworkHubExtensions + { + public static Task RequestFileAsync(this IHubContext hub, string agent, string filename, Guid id) + { + // todo: how to send this to the specified agent? + return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); + } + } + + /// + /// The network SignalR hub. + /// + [Authorize] + public class NetworkHub : Hub + { + public NetworkHub( + INetworkService networkService) + { + Network = networkService; + } + + private INetworkService Network { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + public override async Task OnConnectedAsync() + { + Log.Information("Agent connection {Id} established. Sending authentication challenge...", Context.ConnectionId); + await Clients.Caller.SendAsync(NetworkHubMethods.AuthenticationChallenge, Network.GenerateAuthenticationChallengeToken(Context.ConnectionId)); + } + + public override Task OnDisconnectedAsync(Exception exception) + { + if (Network.TryRemoveAgentRegistration(Context.ConnectionId, out var agent)) + { + Log.Warning("Agent {Agent} (connection {Id}) disconnected", agent, Context.ConnectionId); + } + + return Task.CompletedTask; + } + + public bool Login(string agent, string challengeResponse) + { + if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) + { + Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); + Network.RegisterAgent(agent, Context.ConnectionId); + return true; + } + + Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); + Network.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! + return false; + } + } +} \ No newline at end of file -- cgit v1.2.3 From 30b7cb4d5bdd496ed01ac13cb9841cab7ac6a394 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:48:50 -0500 Subject: add endpoint to allow agents to report failures --- .../Network/API/Controllers/NetworkController.cs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 836921f1..267705a1 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -40,10 +40,6 @@ namespace slskd.Network private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - /// - /// Gets the current state of the application. - /// - /// [HttpPost("files/{id}")] [Authorize] public async Task UploadFile(string id) @@ -79,5 +75,23 @@ namespace slskd.Network return NotFound(); } } + + [HttpDelete("files/{id}")] + [Authorize] + public IActionResult NotifyUploadFailed(string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest("Id is not a valid Guid"); + } + + if (Network.PendingUploads.TryGetValue(guid, out var record)) + { + record.Upload.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); + return NoContent(); + } + + return NotFound(); + } } } -- cgit v1.2.3 From 6e19db2213d491c3d2965c964c40a7129e74f633 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:20:42 -0500 Subject: add UploadShares endpoint --- .../Network/API/Controllers/NetworkController.cs | 33 ++++++++++++++++++---- 1 file changed, 28 insertions(+), 5 deletions(-) (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 267705a1..8f863ce4 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -38,7 +38,7 @@ namespace slskd.Network } private INetworkService Network { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); [HttpPost("files/{id}")] [Authorize] @@ -50,7 +50,7 @@ namespace slskd.Network } // get the record for the waiting file - if (Network.PendingUploads.TryGetValue(guid, out var record)) + if (Network.PendingFileUploads.TryGetValue(guid, out var record)) { // get the stream from the multipart upload var stream = Request.Form.Files.First().OpenReadStream(); @@ -58,7 +58,7 @@ namespace slskd.Network // set the result for the stream // this should pass control to the transfer service along with // the stream - record.Upload.SetResult(stream); + record.Stream.SetResult(stream); Console.WriteLine("Stream handed off. Waiting for completion..."); @@ -85,13 +85,36 @@ namespace slskd.Network return BadRequest("Id is not a valid Guid"); } - if (Network.PendingUploads.TryGetValue(guid, out var record)) + if (Network.PendingFileUploads.TryGetValue(guid, out var record)) { - record.Upload.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); + record.Stream.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); return NoContent(); } return NotFound(); } + + [HttpPost("shares/{id}")] + [Authorize] + public IActionResult UploadShares(string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest("Id is not a valid Guid"); + } + + if (!Network.TryGetShareUploadToken(guid, out var agent)) + { + return Unauthorized(); + } + + // todo: save the uploaded file to a temp location + // todo: open the uploaded file as a sqlite database + // todo: load the contents of the file into the local share database + // while modifying the records somehow to indicate which agent + // is hosting it + + return Ok(); + } } } -- cgit v1.2.3 From a8fe7056791ae7e12130fa0ed5e024e99eb40c3e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:20:59 -0500 Subject: add hub method GetShareUploadToken --- src/slskd/Network/API/Hubs/NetworkHub.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 61ac08f0..becbbed0 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -87,5 +87,16 @@ namespace slskd.Network Network.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! return false; } + + public Guid GetShareUploadToken() + { + if (Network.TryGetAgentRegistration(Context.ConnectionId, out var agent)) + { + return Network.GetShareUploadToken(agent); + } + + // this can happen if the agent attempts to upload before logging in + throw new UnauthorizedAccessException(); + } } } \ No newline at end of file -- cgit v1.2.3 From 35edcb342ded5a9bdc4f0627f0c213b85c033bba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 18:15:53 -0500 Subject: fix operand order --- src/slskd/Network/API/Hubs/NetworkHub.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index becbbed0..78a658d4 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -79,7 +79,7 @@ namespace slskd.Network if (Network.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) { Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); - Network.RegisterAgent(agent, Context.ConnectionId); + Network.RegisterAgent(Context.ConnectionId, agent); return true; } @@ -96,6 +96,7 @@ namespace slskd.Network } // this can happen if the agent attempts to upload before logging in + Log.Information("Agent connection {Id} requested a share upload token, but was not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } } -- cgit v1.2.3 From 4bb2484d7b5f3bd1d0e49f8393c4065fa1e59339 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 18:16:10 -0500 Subject: save to a temp file --- .../Network/API/Controllers/NetworkController.cs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 8f863ce4..69e3d789 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -18,6 +18,7 @@ namespace slskd.Network { using System; + using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; @@ -96,7 +97,7 @@ namespace slskd.Network [HttpPost("shares/{id}")] [Authorize] - public IActionResult UploadShares(string id) + public async Task UploadShares(string id) { if (!Guid.TryParse(id, out var guid)) { @@ -108,11 +109,19 @@ namespace slskd.Network return Unauthorized(); } - // todo: save the uploaded file to a temp location - // todo: open the uploaded file as a sqlite database - // todo: load the contents of the file into the local share database - // while modifying the records somehow to indicate which agent - // is hosting it + var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agent}_{Path.GetRandomFileName()}.db"); + + Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp); + + using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); + using var inputStream = Request.Form.Files.First().OpenReadStream(); + + await inputStream.CopyToAsync(outputStream); + + Log.Debug("Upload of share from {Agent} to {Filename} complete", agent, temp); + + // todo: validate database + // todo: add contents of db to local db return Ok(); } -- cgit v1.2.3 From 5281911a0634bd790adef13e7e0de28d40e9ee4d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 08:04:47 -0500 Subject: add ShareRepositoryFactory, consolidate a lot of OOP cruft --- .../Network/API/Controllers/NetworkController.cs | 25 ++- src/slskd/Network/NetworkClient.cs | 28 ++-- src/slskd/Program.cs | 5 +- src/slskd/Shares/IReadOnlyShareRepository.cs | 26 --- src/slskd/Shares/IReadWriteShareRepository.cs | 96 ----------- src/slskd/Shares/IShareRepository.cs | 89 +++++++++- src/slskd/Shares/IShareRepositoryFactory.cs | 46 ++++++ src/slskd/Shares/IShareService.cs | 13 +- src/slskd/Shares/ShareConnectionStringFactory.cs | 58 ------- src/slskd/Shares/ShareRepositoryFactory.cs | 74 +++++++++ src/slskd/Shares/ShareScanner.cs | 4 +- src/slskd/Shares/ShareService.cs | 64 ++++--- src/slskd/Shares/SqliteShareRepository.cs | 183 ++++++++++++--------- 13 files changed, 384 insertions(+), 327 deletions(-) delete mode 100644 src/slskd/Shares/IReadOnlyShareRepository.cs delete mode 100644 src/slskd/Shares/IReadWriteShareRepository.cs create mode 100644 src/slskd/Shares/IShareRepositoryFactory.cs delete mode 100644 src/slskd/Shares/ShareConnectionStringFactory.cs create mode 100644 src/slskd/Shares/ShareRepositoryFactory.cs (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 69e3d789..deeddc04 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -24,6 +24,7 @@ namespace slskd.Network using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Serilog; + using slskd.Shares; /// /// Network. @@ -33,11 +34,19 @@ namespace slskd.Network [ApiController] public class NetworkController : ControllerBase { - public NetworkController(INetworkService networkService) + public NetworkController( + INetworkService networkService, + IShareService shareService, + IShareRepositoryFactory shareRepositoryFactory) { Network = networkService; + Shares = shareService; + + ShareRepositoryFactory = shareRepositoryFactory; } + private IShareRepositoryFactory ShareRepositoryFactory { get; } + private IShareService Shares { get; } private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -114,14 +123,22 @@ namespace slskd.Network Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); - using var inputStream = Request.Form.Files.First().OpenReadStream(); + using var inputStream = Request.Form.Files[0].OpenReadStream(); await inputStream.CopyToAsync(outputStream); Log.Debug("Upload of share from {Agent} to {Filename} complete", agent, temp); - // todo: validate database - // todo: add contents of db to local db + var repository = ShareRepositoryFactory.CreateFromFile(temp); + + if (!repository.TryValidate(out var problems)) + { + return BadRequest(string.Join(", ", problems)); + } + + var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); + + destinationRepository.RestoreFrom(repository); return Ok(); } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 10e33118..15f114f9 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -127,7 +127,7 @@ namespace slskd.Network Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); Log.Debug("Backing up shares to {Filename}", temp); - Shares.BackupTo($"Data Source={temp};Pooling=False;"); // quite a leaky abstraction + await Shares.DumpAsync(temp); Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); @@ -136,18 +136,22 @@ namespace slskd.Network FileStream stream = default; - try - { - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - } - catch (Exception ex) + while (true) { - // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling - // Pooling=False should be included in the connection string and this shouldn't be an issue, but - // since i don't totally understand the behavior, i'll leave this for now. - Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); - SqliteConnection.ClearAllPools(); - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + try + { + stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + break; + } + catch (Exception ex) + { + // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling + // Pooling=False should be included in the connection string and this shouldn't be an issue, but + // since i don't totally understand the behavior, i'll leave this for now. + Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); + SqliteConnection.ClearAllPools(); + await Task.Delay(100); + } } using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c5d0f961..b9d43992 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -528,10 +528,7 @@ namespace slskd services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(); - services.AddSingleton(new ShareConnectionStringFactory( - createFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, $"shares.{name}")}.db;Cache=shared", - createFromMemory: (name) => $"file:shares.{name}?mode=memory", - createBackupFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, $"shares.{name}")}.db.bak;")); + services.AddTransient(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Shares/IReadOnlyShareRepository.cs b/src/slskd/Shares/IReadOnlyShareRepository.cs deleted file mode 100644 index fff587ad..00000000 --- a/src/slskd/Shares/IReadOnlyShareRepository.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// 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.Shares -{ - /// - /// Read-only persistent storage of shared files and metadata. - /// - public interface IReadOnlyShareRepository : IShareRepository - { - } -} diff --git a/src/slskd/Shares/IReadWriteShareRepository.cs b/src/slskd/Shares/IReadWriteShareRepository.cs deleted file mode 100644 index c6701753..00000000 --- a/src/slskd/Shares/IReadWriteShareRepository.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// 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.Shares -{ - using System; - using Soulseek; - - /// - /// Writeable persistent storage of shared files and metadata. - /// - public interface IReadWriteShareRepository : IShareRepository - { - - /// - /// Creates a new database. - /// - /// - /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case - /// tables are explicitly dropped prior to creation. - /// - /// An optional value that determines whether the existing database should be discarded. - void Create(bool discardExisting = false); - - /// - /// Inserts a directory. - /// - /// The fully qualified local name of the directory. - /// The timestamp to assign to the record. - void InsertDirectory(string name, long timestamp); - - /// - /// Inserts a file. - /// - /// The fully qualified remote path of the file. - /// The fully qualified local path of the file. - /// The timestamp at which the file was last modified, according to the host OS. - /// The Soulseek.File instance representing the file. - /// The timestamp to assign to the record. - void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp); - - /// - /// Inserts a scan record at the specified . - /// - /// The timestamp associated with the scan. - /// The options snapshot at the start of the scan. - void InsertScan(long timestamp, Options.SharesOptions options); - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - void BackupTo(string connectionString); - - /// - /// Restores the current database from the database at the specified . - /// - /// The connection string of the source database. - void RestoreFrom(string connectionString); - - /// - /// Deletes directory records with a timestamp prior to the specified . - /// - /// The timestamp before which to delete directories. - /// The number of records deleted. - long PruneDirectories(long olderThanTimestamp); - - /// - /// Deletes file records with a timestamp prior to the specified . - /// - /// The timestamp before which to delete files. - /// The number of records deleted. - long PruneFiles(long olderThanTimestamp); - - /// - /// Updates the scan started at the specified to set the . - /// - /// The timestamp associated with the scan. - /// The timestamp at the conclusion of the scan. - void UpdateScan(long timestamp, long end); - } -} \ No newline at end of file diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs index 87c2c386..0cf5cd80 100644 --- a/src/slskd/Shares/IShareRepository.cs +++ b/src/slskd/Shares/IShareRepository.cs @@ -17,6 +17,7 @@ namespace slskd.Shares { + using System; using System.Collections.Generic; using Soulseek; @@ -30,6 +31,12 @@ namespace slskd.Shares /// string ConnectionString { get; } + /// + /// Backs the current database up to the database at the specified . + /// + /// The destination repository. + void BackupTo(IShareRepository repository); + /// /// Counts the number of directories in the database. /// @@ -44,6 +51,22 @@ namespace slskd.Shares /// The number of files. int CountFiles(string parentDirectory = null); + /// + /// Creates a new database. + /// + /// + /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case + /// tables are explicitly dropped prior to creation. + /// + /// An optional value that determines whether the existing database should be discarded. + void Create(bool discardExisting = false); + + /// + /// Dumps the contents of the database to a file. + /// + /// The destination file. + void DumpTo(string filename); + /// /// Finds the filename of the file matching the specified . /// @@ -51,6 +74,30 @@ namespace slskd.Shares /// The filename, if found. string FindFilename(string maskedFilename); + /// + /// Inserts a directory. + /// + /// The fully qualified local name of the directory. + /// The timestamp to assign to the record. + void InsertDirectory(string name, long timestamp); + + /// + /// Inserts a file. + /// + /// The fully qualified remote path of the file. + /// The fully qualified local path of the file. + /// The timestamp at which the file was last modified, according to the host OS. + /// The Soulseek.File instance representing the file. + /// The timestamp to assign to the record. + void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp); + + /// + /// Inserts a scan record at the specified . + /// + /// The timestamp associated with the scan. + /// The options snapshot at the start of the scan. + void InsertScan(long timestamp, Options.SharesOptions options); + /// /// Lists all directories. /// @@ -66,6 +113,26 @@ namespace slskd.Shares /// The list of files. IEnumerable ListFiles(string parentDirectory = null, bool includeFullPath = false); + /// + /// Deletes directory records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete directories. + /// The number of records deleted. + long PruneDirectories(long olderThanTimestamp); + + /// + /// Deletes file records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete files. + /// The number of records deleted. + long PruneFiles(long olderThanTimestamp); + + /// + /// Restores the current database from the database at the specified . + /// + /// The destination repository. + void RestoreFrom(IShareRepository repository); + /// /// Searches the database for files matching the specified . /// @@ -74,11 +141,23 @@ namespace slskd.Shares IEnumerable Search(SearchQuery query); /// - /// Attempts to validate the database at the specified , or the - /// default . + /// Attempts to validate the backing database. + /// + /// A value indicating whether the database is valid. + bool TryValidate(); + + /// + /// Attempts to validate the backing database. /// - /// The connection string of the database to validate. + /// The list of problems, if the database is invalid. /// A value indicating whether the database is valid. - bool TryValidate(string connectionString = null); + bool TryValidate(out IEnumerable problems); + + /// + /// Updates the scan started at the specified to set the . + /// + /// The timestamp associated with the scan. + /// The timestamp at the conclusion of the scan. + void UpdateScan(long timestamp, long end); } -} +} \ No newline at end of file diff --git a/src/slskd/Shares/IShareRepositoryFactory.cs b/src/slskd/Shares/IShareRepositoryFactory.cs new file mode 100644 index 00000000..a43f84d9 --- /dev/null +++ b/src/slskd/Shares/IShareRepositoryFactory.cs @@ -0,0 +1,46 @@ +// +// 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.Shares +{ + /// + /// Persistent storage of a shared file cache. + /// + public interface IShareRepositoryFactory + { + /// + /// Create a repository for the specified . + /// + /// The name of the agent. + /// The created repository. + IShareRepository CreateFromHost(string name); + + /// + /// Create a repository backup for the specified . + /// + /// The name of the agent. + /// The created repository. + IShareRepository CreateFromHostBackup(string name); + + /// + /// Create a repository for the specified . + /// + /// The fully qualified path of the filename. + /// The created repository. + IShareRepository CreateFromFile(string filename); + } +} diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 90fa115d..b55db482 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -42,18 +42,19 @@ namespace slskd.Shares /// The host to add or update. void AddOrUpdateHost(Host host); - /// - /// Backs contents of the cache up to the specified file. - /// - /// The destination connection string. - void BackupTo(string connectionString); - /// /// Returns the entire contents of the share. /// /// The entire contents of the share. Task> BrowseAsync(Share share = null); + /// + /// Dumps the local share cache to a file. + /// + /// The destination file. + /// The operation context. + Task DumpAsync(string filename); + /// /// Returns the contents of the specified . /// diff --git a/src/slskd/Shares/ShareConnectionStringFactory.cs b/src/slskd/Shares/ShareConnectionStringFactory.cs deleted file mode 100644 index d9b7492b..00000000 --- a/src/slskd/Shares/ShareConnectionStringFactory.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// 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.Shares -{ - using System; - - /// - /// Creates connection strings for share cache databases. - /// - public class ShareConnectionStringFactory - { - /// - /// Initializes a new instance of the class. - /// - /// The function used to create a connection string for a share cache database. - /// The function used to create an in-memory connection string for a share cache database. - /// The function used to crate a connection string for a share cache backup database. - public ShareConnectionStringFactory( - Func createFromFile, - Func createFromMemory, - Func createBackupFromFile) - { - CreateFromFile = createFromFile; - CreateFromMemory = createFromMemory; - CreateBackupFromFile = createBackupFromFile; - } - - /// - /// Gets a function used to create a connection string for a share cache database. - /// - public Func CreateFromFile { get; } - - /// - /// Gets a function used to create an in-memory connection string for a share cache database. - /// - public Func CreateFromMemory { get; } - - /// - /// Gets a function used to create a connection string for a share cache backup database. - /// - public Func CreateBackupFromFile { get; } - } -} diff --git a/src/slskd/Shares/ShareRepositoryFactory.cs b/src/slskd/Shares/ShareRepositoryFactory.cs new file mode 100644 index 00000000..fc58c397 --- /dev/null +++ b/src/slskd/Shares/ShareRepositoryFactory.cs @@ -0,0 +1,74 @@ +// +// 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 System.IO; + +namespace slskd.Shares +{ + /// + /// Persistent storage of a shared file cache. + /// + public class SqliteShareRepositoryFactory : IShareRepositoryFactory + { + /// + /// Initializes a new instance of the class. + /// + /// + public SqliteShareRepositoryFactory( + OptionsAtStartup optionsAtStartup) + { + StorageMode = optionsAtStartup.Shares.Cache.StorageMode.ToEnum(); + } + + private StorageMode StorageMode { get; } + + /// + /// Create a repository for the specified . + /// + /// The name of the agent. + /// The created repository. + public IShareRepository CreateFromHost(string name) + { + if (StorageMode == StorageMode.Memory) + { + return new SqliteShareRepository($"Data Source=file:shares.{name}?mode=memory;Cache=shared"); + } + + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.db"); + return new SqliteShareRepository($"Data Source={file};Cache=shared"); + } + + /// + /// Create a repository backup for the specified . + /// + /// The name of the agent. + /// The created repository. + public IShareRepository CreateFromHostBackup(string name) + { + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.bak.db"); + return new SqliteShareRepository($"Data Source={file}"); + } + + /// + /// Create a repository for the specified . + /// + /// The fully qualified path of the filename. + /// The created repository. + public IShareRepository CreateFromFile(string filename) + => new SqliteShareRepository($"Data Source={filename}"); + } +} diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index f5e7e52d..7a174396 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -67,7 +67,7 @@ namespace slskd.Shares /// public ShareScanner( int workerCount, - IReadWriteShareRepository shareRepository, + IShareRepository shareRepository, ISoulseekFileFactory soulseekFileFactory = null) { WorkerCount = workerCount; @@ -87,7 +87,7 @@ namespace slskd.Shares private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private CancellationTokenSource CancellationTokenSource { get; set; } - private IReadWriteShareRepository Repository { get; } + private IShareRepository Repository { get; } /// /// Scans the configured shares and fills the cache. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index a0aec286..cc35477e 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -37,32 +37,22 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// - /// + /// /// /// public ShareService( - ShareConnectionStringFactory shareConnectionStringFactory, + IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor optionsMonitor, IShareScanner scanner = null) { var options = optionsMonitor.CurrentValue; - ConnectionStringFactory = shareConnectionStringFactory; CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum(); - if (CacheStorageMode == StorageMode.Memory) - { - ConnectionString = ConnectionStringFactory.CreateFromMemory(options.InstanceName); - } - else - { - ConnectionString = ConnectionStringFactory.CreateFromFile(options.InstanceName); - } - - BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile(options.InstanceName); + ShareRepositoryFactory = shareRepositoryFactory; var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online); - var repository = new SqliteShareRepository(ConnectionString); + var repository = ShareRepositoryFactory.CreateFromHost(options.InstanceName); Local = (host, repository); @@ -108,9 +98,7 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor { get; } - private string ConnectionString { get; } - private string BackupConnectionString { get; } - private ShareConnectionStringFactory ConnectionStringFactory { get; } + private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareScanner Scanner { get; } private string LastOptionsHash { get; set; } private IOptionsMonitor OptionsMonitor { get; } @@ -119,7 +107,7 @@ namespace slskd.Shares private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private (Host Host, IReadWriteShareRepository Repository) Local { get; set; } + private (Host Host, IShareRepository Repository) Local { get; set; } private IEnumerable AllRepositories { get; set; } /// @@ -128,9 +116,11 @@ namespace slskd.Shares /// The host to add or update. public void AddOrUpdateHost(Host host) { + // we assume that if this method is called that the caller has verified that the + // file for the host exists and is valid. HostDictionary.AddOrUpdate( key: host.Name, - addValueFactory: (key) => (host, new SqliteShareRepository(ConnectionStringFactory.CreateFromFile(host.Name))), + addValueFactory: (key) => (host, ShareRepositoryFactory.CreateFromHost(host.Name)), updateValueFactory: (_, existing) => (host, existing.Repository)); AllRepositories = HostDictionary.Values @@ -139,15 +129,6 @@ namespace slskd.Shares .Prepend(Local.Repository); } - /// - /// Backs contents of the cache up to the specified file. - /// - /// The destination connection string. - public void BackupTo(string connectionString) - { - Repository.BackupTo(connectionString); - } - /// /// Returns the entire contents of the share. /// @@ -200,6 +181,17 @@ namespace slskd.Shares return Task.FromResult(results); } + /// + /// Dumps the local share cache to a file. + /// + /// The destination file. + /// The operation context. + public Task DumpAsync(string filename) + { + Local.Repository.DumpTo(filename); + return Task.CompletedTask; + } + /// /// Returns the contents of the specified . /// @@ -272,7 +264,7 @@ namespace slskd.Shares await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares); Log.Debug("Backing up shared file cache database..."); - Local.Repository.BackupTo(BackupConnectionString); + Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName)); Log.Debug("Shared file cache database backup complete"); } @@ -319,11 +311,13 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (Local.Repository.TryValidate(BackupConnectionString)) + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + + if (backupRepository.TryValidate(out _)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Local.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(backupRepository); Log.Information("Share cache successfully restored from backup"); } @@ -337,7 +331,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (Local.Repository.TryValidate(ConnectionString)) + if (Local.Repository.TryValidate(out _)) { // no-op } @@ -345,11 +339,13 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (Local.Repository.TryValidate(BackupConnectionString)) + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + + if (backupRepository.TryValidate(out _)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Local.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(backupRepository); Log.Information("Share cache successfully restored from backup"); } diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 28788c3f..9b65794e 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -28,7 +28,7 @@ namespace slskd.Shares /// /// Persistent storage of shared files and metadata. /// - public class SqliteShareRepository : IReadWriteShareRepository + public class SqliteShareRepository : IShareRepository { /// /// Initializes a new instance of the class. @@ -47,84 +47,13 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Attempts to validate the database at the specified , or the - /// default . + /// Backs the current database up to the database at the specified . /// - /// The connection string of the database to validate. - /// A value indicating whether the database is valid. - public bool TryValidate(string connectionString = null) - { - connectionString ??= ConnectionString; - - // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: - // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' - var schema = new Dictionary() - { - { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, - { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, - { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, - { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, - { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, - { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, - { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, - { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, - { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, - }; - - try - { - Log.Debug("Validating shares database with connection string {String}", connectionString); - - using var conn = new SqliteConnection(connectionString); - conn.Open(); - - using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn); - - var reader = cmd.ExecuteReader(); - var rows = 0; - - while (reader.Read()) - { - var table = reader.GetString(0); - var expectedSql = reader.GetString(1); - - if (schema.TryGetValue(table, out var actualSql)) - { - if (actualSql != expectedSql) - { - throw new MissingFieldException($"Expected {table} schema to be {expectedSql}, found {actualSql}"); - } - else - { - Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); - } - } - - rows++; - } - - if (rows != schema.Count) - { - throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}"); - } - - return true; - } - catch (Exception ex) - { - Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); - return false; - } - } - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - public void BackupTo(string connectionString) + /// The destination repository. + public void BackupTo(IShareRepository repository) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(connectionString); + using var backupConn = GetConnection(repository.ConnectionString); sourceConn.BackupDatabase(backupConn); } @@ -224,6 +153,19 @@ namespace slskd.Shares "extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL);"); } + /// + /// Dumps the contents of the database to a file. + /// + /// The destination file. + public void DumpTo(string filename) + { + using var sourceConn = GetConnection(ConnectionString); + using var backupConn = GetConnection($"Data Source={filename}"); + sourceConn.BackupDatabase(backupConn); + + Sqlite. + } + /// /// Finds the filename of the file matching the specified . /// @@ -442,12 +384,12 @@ namespace slskd.Shares } /// - /// Restores the current database from the database at the specified . + /// Restores the current database from the database at the specified . /// - /// The connection string of the source database. - public void RestoreFrom(string connectionString) + /// The destination repository. + public void RestoreFrom(IShareRepository repository) { - using var sourceConn = GetConnection(connectionString); + using var sourceConn = GetConnection(repository.ConnectionString); using var restoreConn = GetConnection(); sourceConn.BackupDatabase(restoreConn); } @@ -504,6 +446,87 @@ namespace slskd.Shares } } + /// + /// Attempts to validate the backing database. + /// + /// A value indicating whether the database is valid. + public bool TryValidate() + { + return TryValidate(out _); + } + + /// + /// Attempts to validate the backing database. + /// + /// The list of problems, if the database is invalid. + /// A value indicating whether the database is valid. + public bool TryValidate(out IEnumerable problems) + { + var list = new List(); + problems = list; + + // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: + // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' + var schema = new Dictionary() + { + { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, + { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, + { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, + { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, + { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, + { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, + { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, + { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, + { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, + }; + + try + { + Log.Debug("Validating shares database with connection string {String}", ConnectionString); + + using var conn = new SqliteConnection(ConnectionString); + conn.Open(); + + using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn); + + var reader = cmd.ExecuteReader(); + var rows = 0; + + while (reader.Read()) + { + var table = reader.GetString(0); + var expectedSql = reader.GetString(1); + + if (schema.TryGetValue(table, out var actualSql)) + { + if (actualSql != expectedSql) + { + list.Add($"Expected {table} schema to be {expectedSql}, found {actualSql}"); + } + else + { + Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); + } + } + + rows++; + } + + if (rows != schema.Count) + { + list.Add($"Expected {schema.Count} tables, found {rows}"); + } + + return !problems.Any(); + } + catch (Exception ex) + { + Log.Debug(ex, $"Failed to validate database: {ex.Message}"); + list.Add($"Failed to validate database: {ex.Message}"); + return false; + } + } + /// /// Updates the scan started at the specified to set the . /// -- cgit v1.2.3 From a3b23e0e1e9b013f79f9e93a1963a865e3c60ede Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:39:52 -0500 Subject: finish implementation of share uploads --- .../Network/API/Controllers/NetworkController.cs | 36 +++++++++++----------- 1 file changed, 18 insertions(+), 18 deletions(-) (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index deeddc04..21373749 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -18,10 +18,12 @@ namespace slskd.Network { using System; + using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Shares; @@ -86,36 +88,32 @@ namespace slskd.Network } } - [HttpDelete("files/{id}")] + [HttpPost("shares/{id}")] [Authorize] - public IActionResult NotifyUploadFailed(string id) + public async Task UploadShares(string id) { if (!Guid.TryParse(id, out var guid)) { return BadRequest("Id is not a valid Guid"); } - if (Network.PendingFileUploads.TryGetValue(guid, out var record)) + if (!Network.TryGetShareUploadToken(guid, out var agent)) { - record.Stream.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); - return NoContent(); + return Unauthorized(); } - return NotFound(); - } + IEnumerable shares; + IFormFile database; - [HttpPost("shares/{id}")] - [Authorize] - public async Task UploadShares(string id) - { - if (!Guid.TryParse(id, out var guid)) + try { - return BadRequest("Id is not a valid Guid"); + shares = Request.Form["shares"].ToString().FromJson>(); + database = Request.Form.Files[0]; } - - if (!Network.TryGetShareUploadToken(guid, out var agent)) + catch (Exception ex) { - return Unauthorized(); + Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agent, ex.Message); + return BadRequest(); } var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agent}_{Path.GetRandomFileName()}.db"); @@ -123,7 +121,7 @@ namespace slskd.Network Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); - using var inputStream = Request.Form.Files[0].OpenReadStream(); + using var inputStream = database.OpenReadStream(); await inputStream.CopyToAsync(outputStream); @@ -133,13 +131,15 @@ namespace slskd.Network if (!repository.TryValidate(out var problems)) { - return BadRequest(string.Join(", ", problems)); + return BadRequest("Invalid database: " + string.Join(", ", problems)); } var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); destinationRepository.RestoreFrom(repository); + Shares.AddOrUpdateHost(new Host(agent, shares)); + return Ok(); } } -- cgit v1.2.3 From e2383ff98d4994fa2215eb47b8b0cd69775e088b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:40:20 -0500 Subject: add a hub method to handle failed uploads --- src/slskd/Network/API/Hubs/NetworkHub.cs | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 78a658d4..6d43e6da 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -99,5 +99,13 @@ namespace slskd.Network Log.Information("Agent connection {Id} requested a share upload token, but was not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } + + public void NotifyUploadFailed(Guid id) + { + if (Network.PendingFileUploads.TryGetValue(id, out var record)) + { + record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } } } \ No newline at end of file -- cgit v1.2.3 From 8663b3fac9597f7b0c6ffd8081b99c761a18b326 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 19:09:41 -0500 Subject: add file info handling --- src/slskd/Network/API/Hubs/NetworkHub.cs | 16 +++- src/slskd/Network/NetworkClient.cs | 25 +++++- src/slskd/Network/NetworkService.cs | 141 ++++++++++++++++++++++--------- 3 files changed, 139 insertions(+), 43 deletions(-) (limited to 'src/slskd/Network/API') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 6d43e6da..f79fecf2 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -26,6 +26,7 @@ namespace slskd.Network public static class NetworkHubMethods { public static readonly string RequestFile = "REQUEST_FILE"; + public static readonly string RequestFileInfo = "REQUEST_FILE_INFO"; public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; @@ -41,6 +42,11 @@ namespace slskd.Network // todo: how to send this to the specified agent? return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); } + + public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) + { + return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); + } } /// @@ -104,7 +110,15 @@ namespace slskd.Network { if (Network.PendingFileUploads.TryGetValue(id, out var record)) { - record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + record.Stream.TrySetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } + + public void ReturnFileInfo(Guid id, bool exists, long length) + { + if (Network.PendingFileInquiries.TryGetValue(id, out var record)) + { + record.TrySetResult((exists, length)); } } } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index d171e9b9..6e4e4dca 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -156,7 +156,7 @@ namespace slskd.Network Log.Information("Upload shares succeeded"); } - private async Task HandleFileRequest(Guid id, string filename) + private async Task HandleFileRequest(string filename, Guid id) { Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); @@ -164,7 +164,7 @@ namespace slskd.Network { var localFilename = await Shares.ResolveFileAsync(filename); - var localFileInfo = new FileInfo(filename); + var localFileInfo = new FileInfo(localFilename); if (!localFileInfo.Exists) { @@ -202,6 +202,25 @@ namespace slskd.Network } } + private async Task HandleFileInfoRequest(string filename, Guid id) + { + Log.Information("Network controller requested file info for {Filename} with ID {Id}", filename, id); + + try + { + var localFilename = await Shares.ResolveFileAsync(filename); + + var localFileInfo = new FileInfo(localFilename); + + await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message); + await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, false, 0); + } + } + private async Task HandleAuthenticationChallenge(string challengeToken) { Log.Debug("Network controller sent an authentication challenge"); @@ -296,7 +315,7 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); LastOptionsHash = optionsHash; diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 8753ae0a..d857cac5 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -37,11 +37,25 @@ namespace slskd.Network /// ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } + /// + /// Gets the collection of pending Agent file inquiries. + /// + ReadOnlyDictionary> PendingFileInquiries { get; } + /// /// Gets the collection of registered Agents. /// ReadOnlyDictionary RegisteredAgents { get; } + /// + /// Retrieves information about the specified from the specified . + /// + /// The agent from which to retrieve the file information. + /// The file for which to retrieve information. + /// An optional timeout value. + /// A value indicating whether the file exists, and the length in bytes. + Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000); + /// /// Retrieves an upload of the specified from the specified . /// @@ -131,12 +145,18 @@ namespace slskd.Network /// public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); + /// + /// Gets the collection of pending Agent file inquiries. + /// + public ReadOnlyDictionary> PendingFileInquiries => new(PendingFileInquiryDictionary); + /// /// Gets the collection of registered Agents. /// public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IOptionsMonitor OptionsMonitor { get; } @@ -144,6 +164,88 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + /// + /// Retrieves information about the specified from the specified . + /// + /// The agent from which to retrieve the file information. + /// The file for which to retrieve information. + /// An optional timeout value. + /// A value indicating whether the file exists, and the length in bytes. + public async Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + var tcs = new TaskCompletionSource<(bool Exists, long Length)>(); + + PendingFileInquiryDictionary.TryAdd(id, tcs); + + try + { + await NetworkHub.RequestFileInfoAsync(agent, filename, id); + Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agent, id); + + var task = await Task.WhenAny(tcs.Task, Task.Delay(timeout)); + + if (task == tcs.Task) + { + return await tcs.Task; + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve file information for {filename} from Agent {agent}"); + } + } + finally + { + PendingFileInquiryDictionary.TryRemove(id, out _); + } + } + + /// + /// Retrieves an upload 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<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + + // 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 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(id, (upload, completion)); + + try + { + await NetworkHub.RequestFileAsync(agent, filename, id); + Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); + + var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); + + 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 {agent}"); + } + } + finally + { + PendingFileUploadDictionary.TryRemove(id, out _); + } + } + /// /// Retrieves a new share upload token for the specified . /// @@ -249,45 +351,6 @@ namespace slskd.Network return expectedResponse == challengeResponse; } - /// - /// Retrieves an upload 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<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) - { - var id = Guid.NewGuid(); - - // 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 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(id, (upload, completion)); - - await NetworkHub.RequestFileAsync(agent, filename, id); - Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); - - var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); - - 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 {agent}"); - } - } - private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; -- cgit v1.2.3