62 lines
2.0 KiB
C#
62 lines
2.0 KiB
C#
// -----------------------------------------------------------------------------
|
|
// InMemoryHlcStateStore.cs
|
|
// Sprint: SPRINT_20260105_002_001_LB_hlc_core_library
|
|
// Task: HLC-004 - Implement IHlcStateStore interface and InMemoryHlcStateStore
|
|
// -----------------------------------------------------------------------------
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
namespace StellaOps.HybridLogicalClock;
|
|
|
|
/// <summary>
|
|
/// In-memory implementation of HLC state store for testing and development.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// This implementation does not survive process restarts. Use PostgresHlcStateStore
|
|
/// for production deployments requiring persistence.
|
|
/// </remarks>
|
|
public sealed class InMemoryHlcStateStore : IHlcStateStore
|
|
{
|
|
private readonly ConcurrentDictionary<string, HlcTimestamp> _states = new(StringComparer.Ordinal);
|
|
|
|
/// <inheritdoc/>
|
|
public Task<HlcTimestamp?> LoadAsync(string nodeId, CancellationToken ct = default)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
|
ct.ThrowIfCancellationRequested();
|
|
|
|
return Task.FromResult(
|
|
_states.TryGetValue(nodeId, out var timestamp)
|
|
? timestamp
|
|
: (HlcTimestamp?)null);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public Task SaveAsync(HlcTimestamp timestamp, CancellationToken ct = default)
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
|
|
_states.AddOrUpdate(
|
|
timestamp.NodeId,
|
|
timestamp,
|
|
(_, existing) =>
|
|
{
|
|
// Only update if new timestamp is greater (maintain monotonicity)
|
|
return timestamp > existing ? timestamp : existing;
|
|
});
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets all stored states (for testing/debugging).
|
|
/// </summary>
|
|
public IReadOnlyDictionary<string, HlcTimestamp> GetAllStates() =>
|
|
new Dictionary<string, HlcTimestamp>(_states);
|
|
|
|
/// <summary>
|
|
/// Clears all stored states (for testing).
|
|
/// </summary>
|
|
public void Clear() => _states.Clear();
|
|
}
|