-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigurationService.cs
More file actions
183 lines (154 loc) · 5.8 KB
/
Copy pathConfigurationService.cs
File metadata and controls
183 lines (154 loc) · 5.8 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
using System.Text.Json;
using MarketAlly.ProcessMonitor.Interfaces;
using MarketAlly.ProcessMonitor.Models;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace MarketAlly.ProcessMonitor.Services;
/// <summary>
/// Manages application configuration with hot reload support
/// </summary>
public class ConfigurationService : IConfigurationService, IDisposable
{
private readonly ILogger<ConfigurationService> _logger;
private readonly IConfiguration _configuration;
private readonly IMemoryCache _cache;
private readonly IOptionsMonitor<AppSettings> _appSettings;
private readonly FileSystemWatcher _fileWatcher;
private readonly string _configFilePath;
private readonly SemaphoreSlim _configLock = new(1, 1);
public event EventHandler<ProcessConfiguration>? ConfigurationChanged;
public ConfigurationService(
ILogger<ConfigurationService> logger,
IConfiguration configuration,
IMemoryCache cache,
IOptionsMonitor<AppSettings> appSettings)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
_appSettings = appSettings ?? throw new ArgumentNullException(nameof(appSettings));
_configFilePath = Path.Combine(AppContext.BaseDirectory, "processlist.json");
_fileWatcher = InitializeFileWatcher();
}
public async Task<ProcessConfiguration> GetConfigurationAsync()
{
const string cacheKey = "ProcessConfiguration";
if (_cache.TryGetValue<ProcessConfiguration>(cacheKey, out var cached) && cached != null)
{
return cached;
}
await _configLock.WaitAsync();
try
{
// Double-check after acquiring lock
if (_cache.TryGetValue<ProcessConfiguration>(cacheKey, out cached) && cached != null)
{
return cached;
}
var config = await LoadConfigurationAsync();
_cache.Set(cacheKey, config, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(5),
Priority = CacheItemPriority.High
});
return config;
}
finally
{
_configLock.Release();
}
}
public async Task ReloadConfigurationAsync()
{
_logger.LogInformation("Reloading process configuration");
await _configLock.WaitAsync();
try
{
_cache.Remove("ProcessConfiguration");
var config = await LoadConfigurationAsync();
_cache.Set("ProcessConfiguration", config, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(5),
Priority = CacheItemPriority.High
});
ConfigurationChanged?.Invoke(this, config);
_logger.LogInformation("Configuration reloaded successfully");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to reload configuration");
throw;
}
finally
{
_configLock.Release();
}
}
public AppSettings GetAppSettings()
{
return _appSettings.CurrentValue;
}
private async Task<ProcessConfiguration> LoadConfigurationAsync()
{
try
{
if (!File.Exists(_configFilePath))
{
_logger.LogError("Configuration file not found at {Path}", _configFilePath);
throw new FileNotFoundException($"Configuration file not found: {_configFilePath}");
}
var json = await File.ReadAllTextAsync(_configFilePath);
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true
};
var config = JsonSerializer.Deserialize<ProcessConfiguration>(json, options);
if (config == null || config.Processes == null)
{
throw new InvalidOperationException("Invalid configuration format");
}
config.LastModified = File.GetLastWriteTimeUtc(_configFilePath);
_logger.LogInformation("Loaded configuration with {Count} processes", config.Processes.Count);
return config;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error loading configuration from {Path}", _configFilePath);
throw;
}
}
private FileSystemWatcher InitializeFileWatcher()
{
var directory = Path.GetDirectoryName(_configFilePath) ?? AppContext.BaseDirectory;
var fileName = Path.GetFileName(_configFilePath);
var watcher = new FileSystemWatcher(directory, fileName)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
EnableRaisingEvents = true
};
watcher.Changed += async (sender, e) =>
{
// Debounce file changes
await Task.Delay(500);
try
{
_logger.LogInformation("Configuration file changed, reloading");
await ReloadConfigurationAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling configuration file change");
}
};
return watcher;
}
public void Dispose()
{
_fileWatcher?.Dispose();
_configLock?.Dispose();
}
}