RemoteItemMover, Startup/Exit handler refactor

This commit is contained in:
2023-07-26 13:51:17 +02:00
parent 3de71cbdbe
commit 0b36fb939c
23 changed files with 210 additions and 110 deletions

View File

@@ -2,5 +2,5 @@ namespace FileTime.App.Core.Services;
public interface IExitHandler
{
Task ExitAsync();
Task ExitAsync(CancellationToken token = default);
}

View File

@@ -2,5 +2,5 @@ namespace FileTime.App.Core.Services.Persistence;
public interface ITabPersistenceService : IStartupHandler, IExitHandler
{
void SaveStates();
void SaveStates(CancellationToken token = default);
}

View File

@@ -6,7 +6,7 @@ using FileTime.Core.Timeline;
namespace FileTime.App.Core.Services;
public class ContainerRefreshHandler : IStartupHandler, IDisposable
public class ContainerRefreshHandler : IExitHandler
{
private readonly List<IDisposable> _refreshSubscriptions = new();
private List<FullName> _folders = new();
@@ -38,13 +38,13 @@ public class ContainerRefreshHandler : IStartupHandler, IDisposable
);
}
public void Dispose()
public Task ExitAsync(CancellationToken token = default)
{
foreach (var refreshSubscription in _refreshSubscriptions)
{
refreshSubscription.Dispose();
}
}
public Task InitAsync() => Task.CompletedTask;
return Task.CompletedTask;
}
}

View File

@@ -70,14 +70,14 @@ public class TabPersistenceService : ITabPersistenceService
};
}
public Task ExitAsync()
public Task ExitAsync(CancellationToken token = default)
{
SaveStates();
SaveStates(token);
return Task.CompletedTask;
}
private async Task LoadStatesAsync()
private async Task LoadStatesAsync(CancellationToken token = default)
{
if (!File.Exists(_settingsPath))
{
@@ -88,7 +88,7 @@ public class TabPersistenceService : ITabPersistenceService
try
{
await using var stateReader = File.OpenRead(_settingsPath);
var state = await JsonSerializer.DeserializeAsync<PersistenceRoot>(stateReader);
var state = await JsonSerializer.DeserializeAsync<PersistenceRoot>(stateReader, cancellationToken: token);
if (state != null)
{
if (await RestoreTabs(state.TabStates)) return;
@@ -187,7 +187,7 @@ public class TabPersistenceService : ITabPersistenceService
return true;
}
public void SaveStates()
public void SaveStates(CancellationToken token = default)
{
var state = new PersistenceRoot
{
@@ -210,7 +210,7 @@ public class TabPersistenceService : ITabPersistenceService
tabStates.Add(new TabState(currentLocation.FullName!, tab.TabNumber));
}
return new TabStates()
return new TabStates
{
Tabs = tabStates,
ActiveTabNumber = _appState.CurrentSelectedTab?.TabNumber
@@ -218,7 +218,5 @@ public class TabPersistenceService : ITabPersistenceService
}
public async Task InitAsync()
{
await LoadStatesAsync();
}
=> await LoadStatesAsync();
}

View File

@@ -31,7 +31,7 @@ public static class Startup
return serviceCollection
.AddCommandHandlers()
.AddSingleton<IStartupHandler, DefaultIdentifiableCommandHandlerRegister>()
.AddSingleton<IStartupHandler, ContainerRefreshHandler>();
.AddSingleton<IExitHandler, ContainerRefreshHandler>();
}
private static IServiceCollection AddCommandHandlers(this IServiceCollection serviceCollection)

View File

@@ -190,11 +190,11 @@ public partial class FrequencyNavigationService : IFrequencyNavigationService, I
}
}
public async Task ExitAsync() => await SaveStateAsync();
public async Task ExitAsync(CancellationToken token = default) => await SaveStateAsync(token);
private async Task SaveStateAsync()
private async Task SaveStateAsync(CancellationToken token = default)
{
await _saveLock.WaitAsync();
await _saveLock.WaitAsync(token);
try
{
_lastSave = DateTime.Now;

View File

@@ -2,15 +2,20 @@ namespace FileTime.Core.Extensions;
public static class TaskExtensions
{
public static async Task<T?> AwaitWithTimeout<T>(this Task<T> task, int timeout, T? defaultValue = default)
public static async Task TimeoutAfter(this Task task, int timeoutInMilliseconds)
{
if (await Task.WhenAny(task, Task.Delay(timeout)) == task)
if (await Task.WhenAny(task, Task.Delay(timeoutInMilliseconds)) != task)
throw new TimeoutException();
}
public static async Task<T?> TimeoutAfter<T>(this Task<T> task, int timeoutInMilliseconds, T? defaultValue = default)
{
return task.Result;
if (await Task.WhenAny(task, Task.Delay(timeoutInMilliseconds)) == task)
{
return await task;
}
else
{
return defaultValue;
throw new TimeoutException();
}
}
}

View File

@@ -77,7 +77,7 @@ public static class Startup
}
return serviceCollection
.AddSingleton<IStartupHandler, RootDriveInfoService>()
.AddSingleton<IExitHandler, RootDriveInfoService>()
.AddSingleton<IStartupHandler>(sp => sp.GetRequiredService<IPlacesService>());
}

View File

@@ -1,4 +1,5 @@
using FileTime.App.Core.Services;
using FileTime.Core.Extensions;
using Microsoft.Extensions.Logging;
namespace FileTime.GuiApp.Services;
@@ -36,27 +37,30 @@ public class LifecycleService
public async Task ExitAsync()
{
foreach (var exitHandler in _exitHandlers)
var exitCancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var exitHandlerTasks = _exitHandlers.Select(e =>
{
try
{
await exitHandler.ExitAsync();
return e.ExitAsync(exitCancellation.Token);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while running exit handler {Handler}", exitHandler?.GetType().FullName);
}
_logger.LogError(ex, "Error while running exit handler {Handler}", e.GetType().FullName);
}
foreach (var disposable in
_startupHandlers
.OfType<IDisposable>()
.Concat(
_exitHandlers.OfType<IDisposable>()
)
)
return Task.CompletedTask;
});
try
{
disposable.Dispose();
}
await Task.WhenAll(exitHandlerTasks).TimeoutAfter(10000);
}
catch
{
}
exitCancellation.Cancel();
}
}

View File

@@ -7,7 +7,7 @@ using ObservableComputations;
namespace FileTime.GuiApp.Services;
public class RootDriveInfoService : IStartupHandler, IDisposable
public class RootDriveInfoService : IExitHandler
{
private readonly ILocalContentProvider _localContentProvider;
private readonly List<DriveInfo> _rootDrives = new();
@@ -73,6 +73,9 @@ public class RootDriveInfoService : IStartupHandler, IDisposable
return (Path: sourceItem, Drive: rootDrive);
}
public Task InitAsync() => Task.CompletedTask;
public void Dispose() => _rootDriveInfosConsumer.Dispose();
public Task ExitAsync(CancellationToken token = default)
{
_rootDriveInfosConsumer.Dispose();
return Task.CompletedTask;
}
}

View File

@@ -51,7 +51,7 @@ public class WindowsPlacesService : IPlacesService
}
public Dictionary<string, SpecialPathType> GetSpecialPaths()
=> new Dictionary<string, SpecialPathType>
=> new()
{
{KnownFolders.Desktop.Path, SpecialPathType.Desktop},
{KnownFolders.Documents.Path, SpecialPathType.Documents},

View File

@@ -44,12 +44,12 @@ public class LocalItemDeleter : IItemDeleter<ILocalContentProvider>
throw new FileNotFoundException(nativePath);
}
}
catch (Exception e)
catch (Exception ex)
{
_logger.LogDebug(e, "Failed to delete item with path {Path}", nativePath);
_logger.LogDebug(ex, "Failed to delete item with path {Path}", nativePath);
if (!_adminContentAccessorFactory.IsAdminModeSupported
|| e is not UnauthorizedAccessException and not IOException)
|| ex is not UnauthorizedAccessException and not IOException)
{
_logger.LogTrace(
"Admin mode is disabled or exception is not an access denied one, not trying to create {Path} as admin",

View File

@@ -1,28 +1,66 @@
using FileTime.Core.ContentAccess;
using FileTime.Core.Models;
using FileTime.Providers.LocalAdmin;
using Microsoft.Extensions.Logging;
namespace FileTime.Providers.Local;
public class LocalItemMover : IItemMover<ILocalContentProvider>
{
public Task RenameAsync(ILocalContentProvider contentProvider, FullName fullName, FullName newPath)
private readonly IAdminContentAccessorFactory _adminContentAccessorFactory;
private readonly IAdminContentProvider _adminContentProvider;
private readonly ILogger<LocalItemMover> _logger;
public LocalItemMover(
IAdminContentAccessorFactory adminContentAccessorFactory,
IAdminContentProvider adminContentProvider,
ILogger<LocalItemMover> logger)
{
_adminContentAccessorFactory = adminContentAccessorFactory;
_adminContentProvider = adminContentProvider;
_logger = logger;
}
public async Task RenameAsync(ILocalContentProvider contentProvider, FullName fullName, FullName newPath)
{
_logger.LogTrace("Start renaming item {FullName}", fullName);
try
{
var source = contentProvider.GetNativePath(fullName);
var destination = contentProvider.GetNativePath(newPath);
if (File.Exists(source.Path))
{
_logger.LogTrace("File exists with path {Path}", fullName);
File.Move(source.Path, destination.Path);
}
else if (Directory.Exists(source.Path))
{
_logger.LogTrace("Directory exists with path {Path}", fullName);
Directory.Move(source.Path, destination.Path);
}
else
{
_logger.LogTrace("No file or directory exists with path {Path}", fullName);
throw new FileNotFoundException(source.Path);
}
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Failed to rename item {From} to {To}", fullName, newPath);
return Task.CompletedTask;
if (!_adminContentAccessorFactory.IsAdminModeSupported
|| ex is not UnauthorizedAccessException and not IOException)
{
_logger.LogTrace(
"Admin mode is disabled or exception is not an access denied one, not trying to rename {Path} as admin",
fullName
);
throw;
}
var adminItemMover = await _adminContentAccessorFactory.CreateAdminItemMoverAsync();
await adminItemMover.RenameAsync(_adminContentProvider, fullName, newPath);
}
}
}

View File

@@ -7,4 +7,5 @@ public interface IAdminContentAccessorFactory
bool IsAdminModeSupported { get; }
Task<IRemoteItemCreator> CreateAdminItemCreatorAsync();
Task<IRemoteItemDeleter> CreateAdminItemDeleterAsync();
Task<IRemoteItemMover> CreateAdminItemMoverAsync();
}

View File

@@ -1,5 +1,6 @@
using System.Diagnostics;
using FileTime.Providers.Remote;
using FileTime.Server.Common;
using InitableService;
namespace FileTime.Providers.LocalAdmin;
@@ -21,30 +22,26 @@ public class AdminContentAccessorFactory : IAdminContentAccessorFactory
public bool IsAdminModeSupported => _adminElevationManager.IsAdminModeSupported;
public async Task<IRemoteItemCreator> CreateAdminItemCreatorAsync()
{
await _adminElevationManager.CreateAdminInstanceIfNecessaryAsync();
var connection = await _adminElevationManager.CreateConnectionAsync();
Debug.Assert(connection != null);
var adminItemCreator = _serviceProvider.GetInitableResolver(
connection,
_adminElevationManager.ProviderName)
.GetRequiredService<IRemoteItemCreator>();
return adminItemCreator;
}
=> await CreateHelperAsync<IRemoteItemCreator>();
public async Task<IRemoteItemDeleter> CreateAdminItemDeleterAsync()
=> await CreateHelperAsync<IRemoteItemDeleter>();
public async Task<IRemoteItemMover> CreateAdminItemMoverAsync()
=> await CreateHelperAsync<IRemoteItemMover>();
private async Task<T> CreateHelperAsync<T>()
where T : class, IInitable<IRemoteConnection, string>
{
await _adminElevationManager.CreateAdminInstanceIfNecessaryAsync();
var connection = await _adminElevationManager.CreateConnectionAsync();
Debug.Assert(connection != null);
var adminItemDeleter = _serviceProvider.GetInitableResolver(
var helper = _serviceProvider.GetInitableResolver(
connection,
_adminElevationManager.ProviderName)
.GetRequiredService<IRemoteItemDeleter>();
return adminItemDeleter;
.GetRequiredService<T>();
return helper;
}
}

View File

@@ -135,10 +135,7 @@ public class AdminElevationManager : IAdminElevationManager, INotifyPropertyChan
//TODO: use other connections too (if there will be any)
ArgumentNullException.ThrowIfNull(_connectionInfo.SignalRBaseUrl);
var connection = await _serviceProvider
.GetAsyncInitableResolver(_connectionInfo.SignalRBaseUrl)
.GetRequiredServiceAsync<SignalRConnection>();
var connection = await SignalRConnection.GetOrCreateForAsync(_connectionInfo.SignalRBaseUrl);
return connection;
}
catch (Exception ex)
@@ -168,13 +165,14 @@ public class AdminElevationManager : IAdminElevationManager, INotifyPropertyChan
return true;
}
public async Task ExitAsync()
public async Task ExitAsync(CancellationToken token = default)
{
if (!StartProcess)
{
_logger.LogTrace("Not stopping admin process as it was not started by this instance");
return;
}
if (!IsAdminInstanceRunning)
{
_logger.LogTrace("Not stopping admin process as it is not running");
@@ -190,8 +188,19 @@ public class AdminElevationManager : IAdminElevationManager, INotifyPropertyChan
}
catch (Exception ex)
{
_logger.LogError(ex, "Error stopping admin process, trying to kill it");
_adminProcess?.Kill();
_logger.LogError(ex, "Error stopping admin process");
if (_adminProcess is null) return;
for (var i = 0; i < 150 && !_adminProcess.HasExited; i++)
{
await Task.Delay(10);
}
/*if (!_adminProcess.HasExited)
{
_logger.LogInformation("Admin process dit not stopped, killing it");
_adminProcess.Kill();
}*/
}
}
}

View File

@@ -0,0 +1,10 @@
using FileTime.Core.ContentAccess;
using FileTime.Server.Common;
using InitableService;
namespace FileTime.Providers.Remote;
public interface IRemoteItemMover : IItemMover<IRemoteContentProvider>, IInitable<IRemoteConnection, string>
{
}

View File

@@ -0,0 +1,19 @@
using FileTime.Core.Models;
using FileTime.Server.Common;
namespace FileTime.Providers.Remote;
public class RemoteItemMover : IRemoteItemMover
{
private IRemoteConnection _remoteConnection = null!;
private string _remoteContentProviderId = null!;
public void Init(IRemoteConnection remoteConnection, string remoteContentProviderId)
{
_remoteConnection = remoteConnection;
_remoteContentProviderId = remoteContentProviderId;
}
public async Task RenameAsync(IRemoteContentProvider contentProvider, FullName fullName, FullName newPath)
=> await _remoteConnection.MoveItemAsync(_remoteContentProviderId, fullName, newPath);
}

View File

@@ -5,13 +5,12 @@ namespace FileTime.Providers.Remote;
public static class Startup
{
public static IServiceCollection AddRemoteProviderServices(this IServiceCollection serviceCollection)
{
serviceCollection.TryAddSingleton<IRemoteContentProvider, RemoteContentProvider>();
serviceCollection.TryAddTransient<IRemoteItemCreator, RemoteItemCreator>();
serviceCollection.TryAddTransient<IRemoteItemDeleter, RemoteItemDeleter>();
serviceCollection.TryAddTransient<IRemoteItemMover, RemoteItemMover>();
return serviceCollection;
}
}

View File

@@ -8,4 +8,5 @@ public interface IRemoteConnection
Task CreateContainerAsync(string contentProviderId, FullName fullName);
Task CreateElementAsync(string contentProviderId, FullName fullName);
Task DeleteItemAsync(string contentProviderId, FullName fullName);
Task MoveItemAsync(string contentProviderId, FullName fullName, FullName newPath);
}

View File

@@ -6,4 +6,5 @@ public interface ISignalRHub
Task CreateContainerAsync(string contentProviderId, string fullName);
Task CreateElementAsync(string contentProviderId, string fullName);
Task DeleteItemAsync(string contentProviderId, string fullName);
Task MoveItemAsync(string contentProviderId, string fullName, string newPath);
}

View File

@@ -7,10 +7,10 @@ namespace FileTime.Server.Common.Connections.SignalR;
public class SignalRConnection : IRemoteConnection, IAsyncInitable<string>
{
private static readonly Dictionary<string, SignalRConnection> Connections = new();
private string _baseUrl = null!;
private HubConnection _connection = null!;
private ISignalRHub CreateClient() => _connection.CreateHubProxy<ISignalRHub>();
private ISignalRHub _client = null!;
public async Task InitAsync(string baseUrl)
{
@@ -20,29 +20,37 @@ public class SignalRConnection : IRemoteConnection, IAsyncInitable<string>
.WithUrl(_baseUrl)
.Build();
await _connection.StartAsync();
_client = _connection.CreateHubProxy<ISignalRHub>();
}
public static async Task<SignalRConnection> GetOrCreateForAsync(string baseUrl)
{
if (Connections.TryGetValue(baseUrl, out var connection))
{
if (connection._connection.State != HubConnectionState.Disconnected)
{
return connection;
}
Connections.Remove(baseUrl);
}
connection = new SignalRConnection();
Connections.Add(baseUrl, connection);
await connection.InitAsync(baseUrl);
return connection;
}
public async Task Exit()
{
var client = CreateClient();
await client.Exit();
}
=> await _client.Exit();
public async Task CreateContainerAsync(string contentProviderId, FullName fullName)
{
var client = CreateClient();
await client.CreateContainerAsync(contentProviderId, fullName.Path);
}
=> await _client.CreateContainerAsync(contentProviderId, fullName.Path);
public async Task CreateElementAsync(string contentProviderId, FullName fullName)
{
var client = CreateClient();
await client.CreateElementAsync(contentProviderId, fullName.Path);
}
=> await _client.CreateElementAsync(contentProviderId, fullName.Path);
public async Task DeleteItemAsync(string contentProviderId, FullName fullName)
{
var client = CreateClient();
await client.DeleteItemAsync(contentProviderId, fullName.Path);
}
=> await _client.DeleteItemAsync(contentProviderId, fullName.Path);
public async Task MoveItemAsync(string contentProviderId, FullName fullName, FullName newPath)
=> await _client.MoveItemAsync(contentProviderId, fullName.Path, newPath.Path);
}

View File

@@ -49,4 +49,11 @@ public class ConnectionHub : Hub<ISignalRClient>, ISignalRHub
var itemDeleter = _contentAccessorFactory.GetItemDeleter(contentProvider);
await itemDeleter.DeleteAsync(contentProvider, new FullName(fullName));
}
public async Task MoveItemAsync(string contentProviderId, string fullName, string newPath)
{
var contentProvider = _contentProviderRegistry.ContentProviders.First(p => p.Name == contentProviderId);
var itemDeleter = _contentAccessorFactory.GetItemMover(contentProvider);
await itemDeleter.RenameAsync(contentProvider, new FullName(fullName), new FullName(newPath));
}
}