-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileBackedEndpointStateStore.cs
More file actions
396 lines (337 loc) · 13.1 KB
/
FileBackedEndpointStateStore.cs
File metadata and controls
396 lines (337 loc) · 13.1 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using ApiHealthDashboard.Configuration;
using ApiHealthDashboard.Domain;
namespace ApiHealthDashboard.State;
public sealed class FileBackedEndpointStateStore : IEndpointStateStore
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = false
};
private readonly InMemoryEndpointStateStore _innerStore;
private readonly ConcurrentDictionary<string, object> _fileLocks = new(StringComparer.OrdinalIgnoreCase);
private readonly object _cleanupSyncRoot = new();
private readonly object _initializeSyncRoot = new();
private readonly ILogger<FileBackedEndpointStateStore> _logger;
private readonly RuntimeStateOptions _options;
private readonly string _stateDirectoryPath;
private DateTimeOffset _nextCleanupUtc = DateTimeOffset.MinValue;
private HashSet<string> _configuredStateFilePaths = new(StringComparer.OrdinalIgnoreCase);
public FileBackedEndpointStateStore(
IEnumerable<EndpointConfig> endpoints,
string stateDirectoryPath,
RuntimeStateOptions options,
ILogger<FileBackedEndpointStateStore> logger)
{
ArgumentNullException.ThrowIfNull(endpoints);
ArgumentException.ThrowIfNullOrWhiteSpace(stateDirectoryPath);
ArgumentNullException.ThrowIfNull(options);
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_options = options;
_stateDirectoryPath = Path.GetFullPath(stateDirectoryPath);
var endpointList = endpoints
.Where(static endpoint => endpoint is not null)
.Select(static endpoint => endpoint.Clone())
.ToArray();
_innerStore = new InMemoryEndpointStateStore(endpointList);
Directory.CreateDirectory(_stateDirectoryPath);
UpdateConfiguredStateFilePaths(endpointList);
RestorePersistedStates(endpointList, restoreWhenStateIsInitial: true);
TryCleanupPersistedFiles(force: true);
}
public IReadOnlyCollection<EndpointState> GetAll()
{
return _innerStore.GetAll();
}
public EndpointState? Get(string endpointId)
{
return _innerStore.Get(endpointId);
}
public void Upsert(EndpointState state)
{
ArgumentNullException.ThrowIfNull(state);
_innerStore.Upsert(state);
PersistState(state);
TryCleanupPersistedFiles(force: false);
}
public void Initialize(IEnumerable<EndpointConfig> endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
var endpointList = endpoints
.Where(static endpoint => endpoint is not null)
.Select(static endpoint => endpoint.Clone())
.ToArray();
lock (_initializeSyncRoot)
{
_innerStore.Initialize(endpointList);
UpdateConfiguredStateFilePaths(endpointList);
RestorePersistedStates(endpointList, restoreWhenStateIsInitial: true);
TryCleanupPersistedFiles(force: true);
}
}
private void RestorePersistedStates(
IEnumerable<EndpointConfig> endpoints,
bool restoreWhenStateIsInitial)
{
foreach (var endpoint in endpoints)
{
if (endpoint is null || string.IsNullOrWhiteSpace(endpoint.Id))
{
continue;
}
if (restoreWhenStateIsInitial)
{
var currentState = _innerStore.Get(endpoint.Id);
if (currentState is not null && !IsInitialState(currentState))
{
continue;
}
}
var filePath = GetStateFilePath(endpoint.Id);
if (!File.Exists(filePath))
{
continue;
}
try
{
using var stream = File.OpenRead(filePath);
var persistedState = JsonSerializer.Deserialize<PersistedEndpointState>(stream, JsonOptions);
if (persistedState is null)
{
continue;
}
var restoredState = persistedState.ToRuntimeState();
restoredState.EndpointId = endpoint.Id;
restoredState.EndpointName = endpoint.Name;
restoredState.IsPolling = false;
_innerStore.Upsert(restoredState);
_logger.LogInformation(
"Restored persisted runtime state for endpoint {EndpointId} from {StateFilePath}.",
endpoint.Id,
filePath);
}
catch (Exception ex)
{
_logger.LogWarning(
ex,
"Failed to restore persisted runtime state for endpoint {EndpointId} from {StateFilePath}. The endpoint will start with a fresh in-memory state.",
endpoint.Id,
filePath);
}
}
}
private void PersistState(EndpointState state)
{
var endpointId = state.EndpointId;
var stateFilePath = GetStateFilePath(endpointId);
var tempFilePath = $"{stateFilePath}.tmp";
var fileLock = _fileLocks.GetOrAdd(endpointId, static _ => new object());
var persistedState = PersistedEndpointState.FromRuntimeState(state);
lock (fileLock)
{
Directory.CreateDirectory(_stateDirectoryPath);
try
{
using (var stream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
JsonSerializer.Serialize(stream, persistedState, JsonOptions);
stream.Flush(flushToDisk: true);
}
if (File.Exists(stateFilePath))
{
File.Replace(tempFilePath, stateFilePath, destinationBackupFileName: null, ignoreMetadataErrors: true);
}
else
{
File.Move(tempFilePath, stateFilePath);
}
}
catch
{
TryDeleteTempFile(tempFilePath);
throw;
}
}
}
private void UpdateConfiguredStateFilePaths(IEnumerable<EndpointConfig> endpoints)
{
var configuredPaths = endpoints
.Where(static endpoint => endpoint is not null && !string.IsNullOrWhiteSpace(endpoint.Id))
.Select(endpoint => Path.GetFullPath(GetStateFilePath(endpoint.Id)))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
lock (_cleanupSyncRoot)
{
_configuredStateFilePaths = configuredPaths;
}
}
private void TryCleanupPersistedFiles(bool force)
{
if (!_options.CleanupEnabled || !Directory.Exists(_stateDirectoryPath))
{
return;
}
HashSet<string> configuredPaths;
var now = DateTimeOffset.UtcNow;
var cleanupInterval = _options.GetCleanupInterval();
lock (_cleanupSyncRoot)
{
if (!force &&
cleanupInterval > TimeSpan.Zero &&
now < _nextCleanupUtc)
{
return;
}
_nextCleanupUtc = cleanupInterval > TimeSpan.Zero
? now.Add(cleanupInterval)
: now;
configuredPaths = new HashSet<string>(_configuredStateFilePaths, StringComparer.OrdinalIgnoreCase);
}
CleanupOrphanedStateFiles(configuredPaths, now);
}
private void CleanupOrphanedStateFiles(
HashSet<string> configuredPaths,
DateTimeOffset now)
{
if (!_options.DeleteOrphanedStateFiles)
{
return;
}
var retention = _options.GetOrphanedStateFileRetention();
var cutoffUtc = now.UtcDateTime - retention;
foreach (var stateFilePath in Directory.EnumerateFiles(_stateDirectoryPath, "*.state.json", SearchOption.TopDirectoryOnly))
{
var fullStateFilePath = Path.GetFullPath(stateFilePath);
if (configuredPaths.Contains(fullStateFilePath))
{
continue;
}
DateTime lastWriteUtc;
try
{
lastWriteUtc = File.GetLastWriteTimeUtc(fullStateFilePath);
}
catch (Exception ex)
{
_logger.LogWarning(
ex,
"Failed to inspect orphaned runtime state file {StateFilePath} during cleanup.",
fullStateFilePath);
continue;
}
if (retention > TimeSpan.Zero && lastWriteUtc > cutoffUtc)
{
continue;
}
try
{
File.Delete(fullStateFilePath);
_logger.LogInformation(
"Deleted orphaned runtime state file {StateFilePath} during cleanup.",
fullStateFilePath);
}
catch (Exception ex)
{
_logger.LogWarning(
ex,
"Failed to delete orphaned runtime state file {StateFilePath} during cleanup.",
fullStateFilePath);
}
}
}
private string GetStateFilePath(string endpointId)
{
return Path.Combine(_stateDirectoryPath, $"{CreateSafeFileStem(endpointId)}.state.json");
}
private static string CreateSafeFileStem(string endpointId)
{
var sanitizedCharacters = endpointId
.Select(static character => char.IsLetterOrDigit(character) || character is '-' or '_' or '.'
? character
: '-')
.ToArray();
var sanitizedId = new string(sanitizedCharacters).Trim('-');
if (string.IsNullOrWhiteSpace(sanitizedId))
{
sanitizedId = "endpoint";
}
var hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(endpointId));
var hash = Convert.ToHexString(hashBytes.AsSpan(0, 6)).ToLowerInvariant();
return $"{sanitizedId}-{hash}";
}
private static bool IsInitialState(EndpointState state)
{
return state.Status == "Unknown" &&
state.LastCheckedUtc is null &&
state.LastSuccessfulUtc is null &&
state.DurationMs is null &&
string.IsNullOrWhiteSpace(state.LastError) &&
state.Snapshot is null &&
!state.IsPolling;
}
private static void TryDeleteTempFile(string tempFilePath)
{
try
{
if (File.Exists(tempFilePath))
{
File.Delete(tempFilePath);
}
}
catch
{
}
}
private sealed class PersistedEndpointState
{
public string EndpointId { get; set; } = string.Empty;
public string EndpointName { get; set; } = string.Empty;
public string Status { get; set; } = "Unknown";
public DateTimeOffset? LastCheckedUtc { get; set; }
public DateTimeOffset? LastSuccessfulUtc { get; set; }
public long? DurationMs { get; set; }
public string? LastError { get; set; }
public HealthSnapshot? Snapshot { get; set; }
public List<RecentPollSample> RecentSamples { get; set; } = new();
public List<EndpointNotificationDispatch> NotificationDispatches { get; set; } = new();
public static PersistedEndpointState FromRuntimeState(EndpointState state)
{
return new PersistedEndpointState
{
EndpointId = state.EndpointId,
EndpointName = state.EndpointName,
Status = state.Status,
LastCheckedUtc = state.LastCheckedUtc,
LastSuccessfulUtc = state.LastSuccessfulUtc,
DurationMs = state.DurationMs,
LastError = state.LastError,
Snapshot = state.Snapshot?.Clone(),
RecentSamples = state.RecentSamples.Select(static sample => sample.Clone()).ToList(),
NotificationDispatches = state.NotificationDispatches.Select(static dispatch => dispatch.Clone()).ToList()
};
}
public EndpointState ToRuntimeState()
{
return new EndpointState
{
EndpointId = EndpointId,
EndpointName = EndpointName,
Status = Status,
LastCheckedUtc = LastCheckedUtc,
LastSuccessfulUtc = LastSuccessfulUtc,
DurationMs = DurationMs,
LastError = LastError,
Snapshot = Snapshot?.Clone(),
RecentSamples = RecentSamples.Select(static sample => sample.Clone()).ToList(),
NotificationDispatches = NotificationDispatches.Select(static dispatch => dispatch.Clone()).ToList(),
IsPolling = false
};
}
}
}