-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathSettingsManager.cs
More file actions
204 lines (179 loc) · 6.46 KB
/
Copy pathSettingsManager.cs
File metadata and controls
204 lines (179 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
using Google.Protobuf.WellKnownTypes;
using Serilog;
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;
/// <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);
}
/// <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;
}
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);
}
}