-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetaStore.cs
More file actions
79 lines (70 loc) · 2.06 KB
/
Copy pathMetaStore.cs
File metadata and controls
79 lines (70 loc) · 2.06 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
using System.Text.Json;
using OctaneBridge.Models;
namespace OctaneBridge;
public sealed class MetaStore
{
private const int WriteDebounceMs = 200;
private readonly string _path;
private readonly JsonSerializerOptions _jsonOpts;
private readonly object _lock = new();
private OctaneMeta _current;
private CancellationTokenSource? _writeCts;
public event Action<OctaneMeta>? Changed;
public MetaStore(string path, JsonSerializerOptions jsonOpts)
{
_path = path;
_jsonOpts = jsonOpts;
_current = LoadInitial();
}
public OctaneMeta Current
{
get { lock (_lock) return _current; }
}
public void Update(OctaneMeta next)
{
lock (_lock)
{
_current = next;
_writeCts?.Cancel();
var cts = new CancellationTokenSource();
_writeCts = cts;
_ = ScheduleWriteAsync(cts.Token);
}
Changed?.Invoke(next);
}
private OctaneMeta LoadInitial()
{
try
{
if (File.Exists(_path))
{
var json = File.ReadAllText(_path);
var loaded = JsonSerializer.Deserialize<OctaneMeta>(json, _jsonOpts);
if (loaded is not null) return loaded;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"[meta] load failed: {ex.Message}");
}
return new OctaneMeta();
}
private async Task ScheduleWriteAsync(CancellationToken ct)
{
try
{
await Task.Delay(WriteDebounceMs, ct);
OctaneMeta snapshot;
lock (_lock) snapshot = _current;
var json = JsonSerializer.Serialize(snapshot, _jsonOpts);
var tmp = _path + ".tmp";
await File.WriteAllTextAsync(tmp, json, ct);
File.Move(tmp, _path, overwrite: true);
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
Console.Error.WriteLine($"[meta] write failed: {ex.Message}");
}
}
}