Files
mapo-core/MP.IOC/Services/InMemoryWeightProvider.cs
2026-04-10 10:35:30 +02:00

60 lines
1.8 KiB
C#

using MP.Core.DTO;
using System.Collections.Concurrent;
namespace MP.IOC.Services
{
public class InMemoryWeightProvider : IWeightProvider
{
private readonly ConcurrentDictionary<string, (int oldW, int newW)> _map = new();
private readonly int _defaultOld;
private readonly int _defaultNew;
public InMemoryWeightProvider(IConfiguration config)
{
_defaultOld = config.GetValue<int>("RouteMan:DefaultWeightOld", 100);
_defaultNew = config.GetValue<int>("RouteMan:DefaultWeightNew", 0);
}
public (int oldWeight, int newWeight) GetWeightsFor(string method)
{
if (string.IsNullOrEmpty(method)) method = "unknown";
return _map.GetOrAdd(method, _ => (_defaultOld, _defaultNew));
}
public void SetWeights(string method, int oldWeight, int newWeight)
{
_map[method] = (Math.Clamp(oldWeight, 0, 100), Math.Clamp(newWeight, 0, 100));
}
public async Task<List<WeightDTO>> GetAllWeightsAsync()
{
var result = new List<WeightDTO>();
await Task.Delay(1);
foreach (var kvp in _map)
{
result.Add(new WeightDTO
{
Method = kvp.Key,
OldWeight = Math.Clamp(kvp.Value.oldW, 0, 100),
NewWeight = Math.Clamp(kvp.Value.newW, 0, 100)
});
}
return result;
}
public bool UpsertWeight(WeightDTO updRecord)
{
if (updRecord == null || string.IsNullOrEmpty(updRecord.Method))
return false;
_map[updRecord.Method] = (Math.Clamp(updRecord.OldWeight, 0, 100), Math.Clamp(updRecord.NewWeight, 0, 100));
return true;
}
}
}