- Notifications
You must be signed in to change notification settings - Fork3
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
base:main
Are you sure you want to change the base?
Uh oh!
There was an error while loading.Please reload this page.
Changes fromall commits
7465bb5
cd99645
779c11b
fcefec4
39ff83c
07ec725
c21072f
bad5320
065eda1
fc426a8
fa4fbd8
e7b2491
ced517e
File 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 |
---|---|---|
@@ -44,6 +44,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 +94,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 +118,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 +142,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 +155,73 @@ 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. | ||
var syncSessionCts = new CancellationTokenSource(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,204 @@ | ||
using Google.Protobuf.WellKnownTypes; | ||
using Serilog; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. I think this got added by mistake, I can't see any code that uses it | ||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using System.Xml.Linq; | ||
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, new() | ||
{ | ||
/// <summary> | ||
/// Reads the settings from the file system. | ||
/// Always returns the latest settings, even if they were modified by another instance of the app. | ||
/// Returned object is always a fresh instance, so it can be modified without affecting the stored settings. | ||
/// </summary> | ||
/// <param name="ct"></param> | ||
/// <returns></returns> | ||
public 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> | ||
public 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, new() | ||
{ | ||
private readonly string _settingsFilePath; | ||
private readonly string _appName = "CoderDesktop"; | ||
private string _fileName; | ||
private readonly object _lock = new(); | ||
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 (T)_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 result; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Needs to be cloned. | ||
} | ||
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(); | ||
} | ||
} | ||
} | ||
public interface ISettings | ||
{ | ||
/// <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; } | ||
ISettings Clone(); | ||
} | ||
/// <summary> | ||
/// CoderConnect settings class that holds the settings for the CoderConnect feature. | ||
/// </summary> | ||
public class CoderConnectSettings : ISettings | ||
{ | ||
public static string SettingsFileName { get; } = "coder-connect-settings.json"; | ||
public int Version { get; set; } | ||
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 connectOnLogin) | ||
{ | ||
Version = version ?? VERSION; | ||
ConnectOnLaunch = connectOnLogin; | ||
} | ||
ISettings ISettings.Clone() | ||
{ | ||
return Clone(); | ||
} | ||
public CoderConnectSettings Clone() | ||
{ | ||
return new CoderConnectSettings(Version, ConnectOnLaunch); | ||
} | ||
} |
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.