-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathSettingsManager.cs
More file actions
145 lines (129 loc) · 5.01 KB
/
Copy pathSettingsManager.cs
File metadata and controls
145 lines (129 loc) · 5.01 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
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;
/// <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.
/// 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>
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);
}
/// <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();
}
}
}