// -----------------------------------------------------------------------------
// InMemoryHlcStateStore.cs
// Sprint: SPRINT_20260105_002_001_LB_hlc_core_library
// Task: HLC-004 - Implement IHlcStateStore interface and InMemoryHlcStateStore
// -----------------------------------------------------------------------------
namespace StellaOps.HybridLogicalClock;
///
/// In-memory implementation of HLC state store for testing and development.
///
///
/// This implementation does not survive process restarts. Use PostgresHlcStateStore
/// for production deployments requiring persistence.
///
public sealed class InMemoryHlcStateStore : IHlcStateStore
{
private readonly Dictionary _states = new(StringComparer.Ordinal);
private readonly object _lock = new();
///
public Task LoadAsync(string nodeId, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
ct.ThrowIfCancellationRequested();
lock (_lock)
{
return Task.FromResult(
_states.TryGetValue(nodeId, out var timestamp)
? timestamp
: (HlcTimestamp?)null);
}
}
///
public Task SaveAsync(HlcTimestamp timestamp, CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
lock (_lock)
{
if (_states.TryGetValue(timestamp.NodeId, out var existing))
{
// Only update if new timestamp is greater (maintain monotonicity)
if (timestamp > existing)
{
_states[timestamp.NodeId] = timestamp;
}
}
else
{
_states[timestamp.NodeId] = timestamp;
}
}
return Task.CompletedTask;
}
///
/// Gets all stored states (for testing/debugging).
///
public IReadOnlyDictionary GetAllStates() =>
GetAllStatesSnapshot();
///
/// Clears all stored states (for testing).
///
public void Clear()
{
lock (_lock)
{
_states.Clear();
}
}
private IReadOnlyDictionary GetAllStatesSnapshot()
{
lock (_lock)
{
return new Dictionary(_states);
}
}
}