-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
BaseConfigurationHandlerV2.cs
210 lines (186 loc) · 6.26 KB
/
BaseConfigurationHandlerV2.cs
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
205
206
207
208
209
210
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SharedLibraryCore;
using SharedLibraryCore.Interfaces;
namespace IW4MAdmin.Application.IO;
public class BaseConfigurationHandlerV2<TConfigurationType> : IConfigurationHandlerV2<TConfigurationType>
where TConfigurationType : class
{
private readonly ILogger<BaseConfigurationHandlerV2<TConfigurationType>> _logger;
private readonly ConfigurationWatcher _watcher;
private readonly JsonSerializerOptions _serializerOptions = new()
{
WriteIndented = true,
Converters =
{
new JsonStringEnumConverter()
},
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
private readonly SemaphoreSlim _onIo = new(1, 1);
private TConfigurationType _configurationInstance;
private string _path = string.Empty;
private event Action<string> FileUpdated;
public BaseConfigurationHandlerV2(ILogger<BaseConfigurationHandlerV2<TConfigurationType>> logger,
ConfigurationWatcher watcher)
{
_logger = logger;
_watcher = watcher;
FileUpdated += OnFileUpdated;
}
~BaseConfigurationHandlerV2()
{
FileUpdated -= OnFileUpdated;
_watcher.Unregister(_path);
}
public async Task<TConfigurationType> Get(string configurationName,
TConfigurationType defaultConfiguration = default)
{
if (string.IsNullOrWhiteSpace(configurationName))
{
return defaultConfiguration;
}
var cleanName = configurationName.Replace("\\", "").Replace("/", "");
if (string.IsNullOrWhiteSpace(configurationName))
{
return defaultConfiguration;
}
_path = Path.Join(Utilities.OperatingDirectory, "Configuration", $"{cleanName}.json");
TConfigurationType readConfiguration = null;
try
{
await _onIo.WaitAsync();
await using var fileStream = File.OpenRead(_path);
readConfiguration =
await JsonSerializer.DeserializeAsync<TConfigurationType>(fileStream, _serializerOptions);
_watcher.Register(_path, FileUpdated);
if (readConfiguration is null)
{
_logger.LogError("Could not parse configuration {Type} at {FileName}", typeof(TConfigurationType).Name,
_path);
return defaultConfiguration;
}
}
catch (FileNotFoundException)
{
if (defaultConfiguration is not null)
{
await InternalSet(defaultConfiguration, false);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Could not read configuration file at {Path}", _path);
return defaultConfiguration;
}
finally
{
if (_onIo.CurrentCount == 0)
{
_onIo.Release(1);
}
}
return _configurationInstance ??= readConfiguration;
}
public async Task Set(TConfigurationType configuration)
{
await InternalSet(configuration, true);
}
public async Task Set()
{
if (_configurationInstance is not null)
{
await InternalSet(_configurationInstance, true);
}
}
public event Action<TConfigurationType> Updated;
private async Task InternalSet(TConfigurationType configuration, bool awaitSemaphore)
{
try
{
if (awaitSemaphore)
{
await _onIo.WaitAsync();
}
await using var fileStream = File.Create(_path);
await JsonSerializer.SerializeAsync(fileStream, configuration, _serializerOptions);
_configurationInstance = configuration;
}
catch (Exception ex)
{
_logger.LogError(ex, "Could not save configuration {Type} {Path}", configuration.GetType().Name, _path);
}
finally
{
if (awaitSemaphore && _onIo.CurrentCount == 0)
{
_onIo.Release(1);
}
}
}
private async void OnFileUpdated(string filePath)
{
try
{
await _onIo.WaitAsync();
await using var fileStream = File.OpenRead(_path);
var readConfiguration =
await JsonSerializer.DeserializeAsync<TConfigurationType>(fileStream, _serializerOptions);
if (readConfiguration is null)
{
_logger.LogWarning("Could not parse updated configuration {Type} at {Path}",
typeof(TConfigurationType).Name, filePath);
}
else
{
CopyUpdatedProperties(readConfiguration);
Updated?.Invoke(readConfiguration);
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Could not parse updated configuration {Type} at {Path}",
typeof(TConfigurationType).Name, filePath);
}
finally
{
if (_onIo.CurrentCount == 0)
{
_onIo.Release(1);
}
}
}
private void CopyUpdatedProperties(TConfigurationType newConfiguration)
{
if (_configurationInstance is null)
{
_configurationInstance = newConfiguration;
return;
}
_logger.LogDebug("Updating existing config with new values {Type} at {Path}", typeof(TConfigurationType).Name,
_path);
if (_configurationInstance is IDictionary configDict && newConfiguration is IDictionary newConfigDict)
{
configDict.Clear();
foreach (var key in newConfigDict.Keys)
{
configDict.Add(key, newConfigDict[key]);
}
}
else
{
foreach (var property in _configurationInstance.GetType().GetProperties()
.Where(prop => prop.CanRead && prop.CanWrite))
{
property.SetValue(_configurationInstance, property.GetValue(newConfiguration));
}
}
}
}