mirror of
https://github.com/AlexMacocian/ServerManagementUtils.git
synced 2026-07-22 18:49:45 +00:00
65 lines
1.8 KiB
C#
65 lines
1.8 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Core.Extensions;
|
|
using System.Text.Json;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using Robin.Options;
|
|
using Robin.Serialization;
|
|
|
|
namespace Robin.Services.Persistence;
|
|
|
|
public sealed class PositionPersistenceService
|
|
{
|
|
private readonly PositionPersistenceOptions options;
|
|
private readonly ConcurrentDictionary<string, long> positions = new();
|
|
|
|
public PositionPersistenceService(
|
|
IOptions<PositionPersistenceOptions> options,
|
|
ILogger<PositionPersistenceService> logger
|
|
)
|
|
{
|
|
this.options = options.Value;
|
|
this.options.FilePath.ThrowIfNull();
|
|
|
|
try
|
|
{
|
|
if (File.Exists(this.options.FilePath))
|
|
{
|
|
this.positions =
|
|
JsonSerializer.Deserialize(
|
|
File.ReadAllText(this.options.FilePath),
|
|
SerializationContext.Default.ConcurrentDictionaryStringInt64
|
|
) ?? new ConcurrentDictionary<string, long>();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Failed to load positions from file.");
|
|
}
|
|
|
|
this.positions ??= [];
|
|
}
|
|
|
|
public async ValueTask SavePositionAsync(
|
|
string source,
|
|
long position,
|
|
CancellationToken cancellationToken
|
|
)
|
|
{
|
|
this.positions[source] = position;
|
|
await File.WriteAllTextAsync(
|
|
this.options.FilePath.ThrowIfNull(),
|
|
JsonSerializer.Serialize(
|
|
this.positions,
|
|
SerializationContext.Default.ConcurrentDictionaryStringInt64
|
|
),
|
|
cancellationToken
|
|
);
|
|
}
|
|
|
|
public long GetPosition(string source)
|
|
{
|
|
return this.positions.GetOrAdd(source, 0);
|
|
}
|
|
}
|