- Notifications
You must be signed in to change notification settings - Fork10
added new settings dialog + settings manager#113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Uh oh!
There was an error while loading.Please reload this page.
Changes fromall commits
7465bb5cd99645779c11bfcefec439ff83c07ec725c21072fbad5320065eda1fc426a8fa4fbd8e7b2491ced517ec4c52e20c7567b2824bd8c11f6db043c9bbFile filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,5 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| @@ -44,6 +43,10 @@ public partial class App : Application | ||
| private readonly ILogger<App> _logger; | ||
| private readonly IUriHandler _uriHandler; | ||
| private readonly ISettingsManager<CoderConnectSettings> _settingsManager; | ||
| private readonly IHostApplicationLifetime _appLifetime; | ||
| public App() | ||
| { | ||
| var builder = Host.CreateApplicationBuilder(); | ||
| @@ -90,6 +93,13 @@ public App() | ||
| // FileSyncListMainPage is created by FileSyncListWindow. | ||
| services.AddTransient<FileSyncListWindow>(); | ||
| services.AddSingleton<ISettingsManager<CoderConnectSettings>, SettingsManager<CoderConnectSettings>>(); | ||
| services.AddSingleton<IStartupManager, StartupManager>(); | ||
| // SettingsWindow views and view models | ||
| services.AddTransient<SettingsViewModel>(); | ||
| // SettingsMainPage is created by SettingsWindow. | ||
| services.AddTransient<SettingsWindow>(); | ||
| // DirectoryPickerWindow views and view models are created by FileSyncListViewModel. | ||
| // TrayWindow views and view models | ||
| @@ -107,8 +117,10 @@ public App() | ||
| services.AddTransient<TrayWindow>(); | ||
| _services = services.BuildServiceProvider(); | ||
| _logger = _services.GetRequiredService<ILogger<App>>(); | ||
| _uriHandler = _services.GetRequiredService<IUriHandler>(); | ||
| _settingsManager = _services.GetRequiredService<ISettingsManager<CoderConnectSettings>>(); | ||
| _appLifetime = _services.GetRequiredService<IHostApplicationLifetime>(); | ||
| InitializeComponent(); | ||
| } | ||
| @@ -129,58 +141,8 @@ public async Task ExitApplication() | ||
| protected override void OnLaunched(LaunchActivatedEventArgs args) | ||
| { | ||
| _logger.LogInformation("new instance launched"); | ||
| _ = InitializeServicesAsync(_appLifetime.ApplicationStopping); | ||
| // Prevent the TrayWindow from closing, just hide it. | ||
| var trayWindow = _services.GetRequiredService<TrayWindow>(); | ||
| @@ -192,6 +154,74 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) | ||
| }; | ||
| } | ||
| /// <summary> | ||
| /// Loads stored VPN credentials, reconnects the RPC controller, | ||
| /// and (optionally) starts the VPN tunnel on application launch. | ||
| /// </summary> | ||
| private async Task InitializeServicesAsync(CancellationToken cancellationToken = default) | ||
ibetitsmike marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| { | ||
| var credentialManager = _services.GetRequiredService<ICredentialManager>(); | ||
| var rpcController = _services.GetRequiredService<IRpcController>(); | ||
| using var credsCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); | ||
| credsCts.CancelAfter(TimeSpan.FromSeconds(15)); | ||
| var loadCredsTask = credentialManager.LoadCredentials(credsCts.Token); | ||
| var reconnectTask = rpcController.Reconnect(cancellationToken); | ||
| var settingsTask = _settingsManager.Read(cancellationToken); | ||
| var dependenciesLoaded = true; | ||
| try | ||
| { | ||
| await Task.WhenAll(loadCredsTask, reconnectTask, settingsTask); | ||
| } | ||
| catch (Exception) | ||
| { | ||
| if (loadCredsTask.IsFaulted) | ||
| _logger.LogError(loadCredsTask.Exception!.GetBaseException(), | ||
| "Failed to load credentials"); | ||
| if (reconnectTask.IsFaulted) | ||
| _logger.LogError(reconnectTask.Exception!.GetBaseException(), | ||
| "Failed to connect to VPN service"); | ||
| if (settingsTask.IsFaulted) | ||
| _logger.LogError(settingsTask.Exception!.GetBaseException(), | ||
| "Failed to fetch Coder Connect settings"); | ||
| // Don't attempt to connect if we failed to load credentials or reconnect. | ||
| // This will prevent the app from trying to connect to the VPN service. | ||
| dependenciesLoaded = false; | ||
| } | ||
| var attemptCoderConnection = settingsTask.Result?.ConnectOnLaunch ?? false; | ||
| if (dependenciesLoaded && attemptCoderConnection) | ||
| { | ||
| try | ||
| { | ||
| await rpcController.StartVpn(cancellationToken); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError(ex, "Failed to connect on launch"); | ||
| } | ||
| } | ||
| // Initialize file sync. | ||
| using var syncSessionCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); | ||
| syncSessionCts.CancelAfter(TimeSpan.FromSeconds(10)); | ||
| var syncSessionController = _services.GetRequiredService<ISyncSessionController>(); | ||
| try | ||
| { | ||
| await syncSessionController.RefreshState(syncSessionCts.Token); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError($"Failed to refresh sync session state {ex.Message}", ex); | ||
| } | ||
| } | ||
| public void OnActivated(object? sender, AppActivationArguments args) | ||
| { | ||
| switch (args.Kind) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| namespace Coder.Desktop.App.Models; | ||
| public interface ISettings<T> : ICloneable<T> | ||
| { | ||
| /// <summary> | ||
| /// FileName where the settings are stored. | ||
| /// </summary> | ||
| static abstract string SettingsFileName { get; } | ||
| /// <summary> | ||
| /// Gets the version of the settings schema. | ||
| /// </summary> | ||
| int Version { get; } | ||
| } | ||
| public interface ICloneable<T> | ||
| { | ||
| /// <summary> | ||
| /// Creates a deep copy of the settings object. | ||
| /// </summary> | ||
| /// <returns>A new instance of the settings object with the same values.</returns> | ||
| T Clone(); | ||
| } | ||
| /// <summary> | ||
| /// CoderConnect settings class that holds the settings for the CoderConnect feature. | ||
| /// </summary> | ||
| public class CoderConnectSettings : ISettings<CoderConnectSettings> | ||
| { | ||
| public static string SettingsFileName { get; } = "coder-connect-settings.json"; | ||
| public int Version { get; set; } | ||
| /// <summary> | ||
| /// When this is true, CoderConnect will automatically connect to the Coder VPN when the application starts. | ||
| /// </summary> | ||
| public bool ConnectOnLaunch { get; set; } | ||
| /// <summary> | ||
| /// CoderConnect current settings version. Increment this when the settings schema changes. | ||
| /// In future iterations we will be able to handle migrations when the user has | ||
| /// an older version. | ||
| /// </summary> | ||
| private const int VERSION = 1; | ||
| public CoderConnectSettings() | ||
| { | ||
| Version = VERSION; | ||
| ConnectOnLaunch = false; | ||
| } | ||
| public CoderConnectSettings(int? version, bool connectOnLaunch) | ||
| { | ||
| Version = version ?? VERSION; | ||
| ConnectOnLaunch = connectOnLaunch; | ||
| } | ||
| public CoderConnectSettings Clone() | ||
| { | ||
| return new CoderConnectSettings(Version, ConnectOnLaunch); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| using System; | ||
| using System.IO; | ||
| using System.Text.Json; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Coder.Desktop.App.Models; | ||
| namespace Coder.Desktop.App.Services; | ||
ibetitsmike marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| /// <summary> | ||
| /// Settings contract exposing properties for app settings. | ||
| /// </summary> | ||
| public interface ISettingsManager<T> where T : ISettings<T>, new() | ||
| { | ||
| /// <summary> | ||
| /// Reads the settings from the file system or returns from cache if available. | ||
| /// Returned object is always a cloned instance, so it can be modified without affecting the stored settings. | ||
| /// </summary> | ||
| /// <param name="ct"></param> | ||
| /// <returns></returns> | ||
| Task<T> Read(CancellationToken ct = default); | ||
| /// <summary> | ||
| /// Writes the settings to the file system. | ||
| /// </summary> | ||
| /// <param name="settings">Object containing the settings.</param> | ||
| /// <param name="ct"></param> | ||
| /// <returns></returns> | ||
| Task Write(T settings, CancellationToken ct = default); | ||
| } | ||
ibetitsmike marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| /// <summary> | ||
| /// Implemention of <see cref="ISettingsManager"/> that persists settings to a JSON file | ||
| /// located in the user's local application data folder. | ||
| /// </summary> | ||
| public sealed class SettingsManager<T> : ISettingsManager<T> where T : ISettings<T>, new() | ||
| { | ||
| private readonly string _settingsFilePath; | ||
| private readonly string _appName = "CoderDesktop"; | ||
| private string _fileName; | ||
| private T? _cachedSettings; | ||
| private readonly SemaphoreSlim _gate = new(1, 1); | ||
| private static readonly TimeSpan LockTimeout = TimeSpan.FromSeconds(3); | ||
| /// <param name="settingsFilePath"> | ||
| /// For unit‑tests you can pass an absolute path that already exists. | ||
| /// Otherwise the settings file will be created in the user's local application data folder. | ||
| /// </param> | ||
| public SettingsManager(string? settingsFilePath = null) | ||
| { | ||
| if (settingsFilePath is null) | ||
| { | ||
| settingsFilePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); | ||
| } | ||
| else if (!Path.IsPathRooted(settingsFilePath)) | ||
| { | ||
| throw new ArgumentException("settingsFilePath must be an absolute path if provided", nameof(settingsFilePath)); | ||
| } | ||
| var folder = Path.Combine( | ||
| settingsFilePath, | ||
| _appName); | ||
| Directory.CreateDirectory(folder); | ||
| _fileName = T.SettingsFileName; | ||
| _settingsFilePath = Path.Combine(folder, _fileName); | ||
| } | ||
| public async Task<T> Read(CancellationToken ct = default) | ||
| { | ||
| if (_cachedSettings is not null) | ||
| { | ||
| // return cached settings if available | ||
| return _cachedSettings.Clone(); | ||
| } | ||
| // try to get the lock with short timeout | ||
| if (!await _gate.WaitAsync(LockTimeout, ct).ConfigureAwait(false)) | ||
| throw new InvalidOperationException( | ||
| $"Could not acquire the settings lock within {LockTimeout.TotalSeconds} s."); | ||
| try | ||
| { | ||
| if (!File.Exists(_settingsFilePath)) | ||
| return new(); | ||
| var json = await File.ReadAllTextAsync(_settingsFilePath, ct) | ||
| .ConfigureAwait(false); | ||
| // deserialize; fall back to default(T) if empty or malformed | ||
| var result = JsonSerializer.Deserialize<T>(json)!; | ||
| _cachedSettings = result; | ||
| return _cachedSettings.Clone(); // return a fresh instance of the settings | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| throw; // propagate caller-requested cancellation | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| throw new InvalidOperationException( | ||
| $"Failed to read settings from {_settingsFilePath}. " + | ||
| "The file may be corrupted, malformed or locked.", ex); | ||
| } | ||
| finally | ||
| { | ||
| _gate.Release(); | ||
| } | ||
| } | ||
| public async Task Write(T settings, CancellationToken ct = default) | ||
| { | ||
| // try to get the lock with short timeout | ||
| if (!await _gate.WaitAsync(LockTimeout, ct).ConfigureAwait(false)) | ||
| throw new InvalidOperationException( | ||
| $"Could not acquire the settings lock within {LockTimeout.TotalSeconds} s."); | ||
| try | ||
| { | ||
| // overwrite the settings file with the new settings | ||
| var json = JsonSerializer.Serialize( | ||
| settings, new JsonSerializerOptions() { WriteIndented = true }); | ||
| _cachedSettings = settings; // cache the settings | ||
| await File.WriteAllTextAsync(_settingsFilePath, json, ct) | ||
| .ConfigureAwait(false); | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| throw; // let callers observe cancellation | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| throw new InvalidOperationException( | ||
| $"Failed to persist settings to {_settingsFilePath}. " + | ||
| "The file may be corrupted, malformed or locked.", ex); | ||
| } | ||
| finally | ||
| { | ||
| _gate.Release(); | ||
| } | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.