Add braces to single-statement guards and refactor NordPool price fetching
- Expand inline guard, return and logger blocks across the monitor services, init classes and tests - Have INordPoolPriceService take a per-date fetch delegate and expose ParseAndAdjust, moving the HA fetch call into NordPoolInit so the service can be registered singleton - Record the NordPool and boiler service lifetimes in AGENTS.md - Drop the unused persisted-state argument from the boiler test data helper
This commit is contained in:
@@ -6,8 +6,7 @@ namespace NordPoolManager;
|
||||
|
||||
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
||||
{
|
||||
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
|
||||
double priceCap, DateTime deadline)
|
||||
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline)
|
||||
{
|
||||
if (prices.Prices is not { Count: > 0 })
|
||||
{
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Text.Json;
|
||||
using NordPool.Models;
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
@@ -11,9 +12,10 @@ public interface INordPoolPriceService
|
||||
DateTime? LastUpdatedDate { get; }
|
||||
DateOnly? LastFetchedDate { get; }
|
||||
|
||||
Task FetchPricesAsync();
|
||||
Task FetchPricesAsync(Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate);
|
||||
NordPoolPrice ParseAndAdjust(JsonElement? element);
|
||||
void UpdateCurrentPrice();
|
||||
double GetCurrentPrice();
|
||||
bool ShouldFetchNewPrices(DateOnly today);
|
||||
void RollOverPrices(DateOnly today);
|
||||
bool ShouldFetchNewPrices(DateOnly dateOnly);
|
||||
void RollOverPrices(DateOnly date);
|
||||
}
|
||||
@@ -77,16 +77,20 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
|
||||
|
||||
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
|
||||
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
||||
}
|
||||
|
||||
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
|
||||
cheapestCount, ctx.IsNowCheap);
|
||||
}
|
||||
|
||||
var updateTasks = new[]
|
||||
{
|
||||
|
||||
@@ -25,10 +25,12 @@ public class NordPoolInit
|
||||
private readonly NordPoolOptions _options;
|
||||
private readonly INordPoolPriceService _priceService;
|
||||
private readonly IScheduler _scheduler;
|
||||
private readonly Services _services;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
|
||||
public NordPoolInit(
|
||||
Entities entities,
|
||||
Services services,
|
||||
IHaContext haContext,
|
||||
ILogger<NordPoolInit> logger,
|
||||
INordPoolPriceService priceService,
|
||||
@@ -44,6 +46,7 @@ public class NordPoolInit
|
||||
_priceService = priceService;
|
||||
_entityService = entityService;
|
||||
_scheduler = scheduler;
|
||||
_services = services;
|
||||
_cheapestIntervalsFinder = cheapestIntervalsFinder;
|
||||
_boilerConfigProvider = boilerConfigProvider;
|
||||
_options = options.Value;
|
||||
@@ -115,10 +118,12 @@ public class NordPoolInit
|
||||
var today = DateOnly.FromDateTime(nowCet);
|
||||
|
||||
if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today)
|
||||
{
|
||||
_priceService.RollOverPrices(today);
|
||||
}
|
||||
|
||||
if (_priceService.ShouldFetchNewPrices(today)) await _priceService.FetchPricesAsync();
|
||||
|
||||
await _priceService.FetchPricesAsync(FetchPricesForDateAsync);
|
||||
|
||||
_priceService.UpdateCurrentPrice();
|
||||
|
||||
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
|
||||
@@ -131,6 +136,20 @@ public class NordPoolInit
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<NordPoolPrice> FetchPricesForDateAsync(DateOnly date)
|
||||
{
|
||||
var nordPoolPricesDto = await _services.Nordpool.GetPricesForDateAsync(
|
||||
new NordpoolGetPricesForDateParameters
|
||||
{
|
||||
Areas = "LT",
|
||||
ConfigEntry = NordPoolConsts.ConfigEntry,
|
||||
Currency = "EUR",
|
||||
Date = date
|
||||
});
|
||||
|
||||
return _priceService.ParseAndAdjust(nordPoolPricesDto);
|
||||
}
|
||||
|
||||
private void SubscribeToFetchPricesButton()
|
||||
{
|
||||
var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId);
|
||||
@@ -157,8 +176,7 @@ public class NordPoolInit
|
||||
return;
|
||||
}
|
||||
|
||||
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice,
|
||||
effectiveIntervalCount, effectivePriceCap, config.Deadline);
|
||||
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Text.Json;
|
||||
using AutoMapper;
|
||||
using HomeAssistantGenerated;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NordPool.Models;
|
||||
using NordPool.Models.Dtos;
|
||||
@@ -9,11 +8,13 @@ using NordPoolManager.Models.Consts;
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public class NordPoolPriceService(Services services, IMapper mapper, ILogger<NordPoolPriceService> logger)
|
||||
: INordPoolPriceService
|
||||
/// <summary>
|
||||
/// Holds NordPool price state and performs price math. Must stay free of
|
||||
/// <c>IHaContext</c>/generated entity dependencies so it can be a singleton.
|
||||
/// Fetching prices from Home Assistant lives in <see cref="NordPoolInit" />.
|
||||
/// </summary>
|
||||
public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService> logger) : INordPoolPriceService
|
||||
{
|
||||
private readonly NordpoolServices _nordPoolServices = services.Nordpool;
|
||||
|
||||
public NordPoolPrice? TodayNordPoolPrice { get; internal set; }
|
||||
public NordPoolPrice? TomorrowNordPoolPrice { get; internal set; }
|
||||
public double CurrentPrice { get; internal set; }
|
||||
@@ -21,31 +22,34 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
public DateTime? LastUpdatedDate { get; private set; }
|
||||
public DateOnly? LastFetchedDate { get; internal set; }
|
||||
|
||||
public async Task FetchPricesAsync()
|
||||
public async Task FetchPricesAsync(Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
|
||||
{
|
||||
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
||||
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
|
||||
var today = DateOnly.FromDateTime(nowCet);
|
||||
var dateNow = DateOnly.FromDateTime(nowCet);
|
||||
|
||||
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today))
|
||||
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(dateNow))
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
|
||||
{
|
||||
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", dateNow);
|
||||
}
|
||||
|
||||
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today");
|
||||
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow, fetchPricesForDate);
|
||||
}
|
||||
|
||||
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) &&
|
||||
ShouldFetchNewPrices(today.AddDays(1)))
|
||||
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(dateNow.AddDays(1)))
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
|
||||
{
|
||||
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", dateNow.AddDays(1));
|
||||
}
|
||||
|
||||
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
|
||||
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow.AddDays(1), fetchPricesForDate);
|
||||
}
|
||||
|
||||
LastUpdatedDate = DateTime.UtcNow;
|
||||
LastFetchedDate = today;
|
||||
LastFetchedDate = dateNow;
|
||||
}
|
||||
|
||||
public void UpdateCurrentPrice()
|
||||
@@ -53,8 +57,9 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
var index = GetTimeQuarterIndex(DateTime.UtcNow);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index,
|
||||
TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
{
|
||||
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
|
||||
if (DayQuartersIndex == index) return;
|
||||
|
||||
@@ -63,14 +68,17 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
var price = TodayNordPoolPrice.Prices[index].Price;
|
||||
|
||||
if (price.HasValue)
|
||||
{
|
||||
CurrentPrice = price.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogWarning("Price at index {Index} is null", index);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}",
|
||||
index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
|
||||
DayQuartersIndex = index;
|
||||
@@ -81,11 +89,11 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
return CurrentPrice;
|
||||
}
|
||||
|
||||
public bool ShouldFetchNewPrices(DateOnly today)
|
||||
public bool ShouldFetchNewPrices(DateOnly date)
|
||||
{
|
||||
if (!LastFetchedDate.HasValue) return true;
|
||||
|
||||
if (LastFetchedDate.Value < today) return true;
|
||||
if (LastFetchedDate.Value < date) return true;
|
||||
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true;
|
||||
|
||||
@@ -96,7 +104,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
return currentHour >= 13;
|
||||
}
|
||||
|
||||
public void RollOverPrices(DateOnly today)
|
||||
public void RollOverPrices(DateOnly date)
|
||||
{
|
||||
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 }
|
||||
? TomorrowNordPoolPrice
|
||||
@@ -105,59 +113,19 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
TomorrowNordPoolPrice = null;
|
||||
|
||||
DayQuartersIndex = -1;
|
||||
LastFetchedDate = today;
|
||||
LastFetchedDate = date;
|
||||
}
|
||||
|
||||
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, string label)
|
||||
public NordPoolPrice ParseAndAdjust(JsonElement? element)
|
||||
{
|
||||
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
|
||||
try
|
||||
{
|
||||
return await GetNordPoolPriceAsync(date);
|
||||
}
|
||||
catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts)
|
||||
{
|
||||
var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1));
|
||||
logger.LogWarning(ex,
|
||||
"Attempt {Attempt}/{MaxAttempts} to fetch {Label} prices for {Date} failed. Retrying in {Delay}",
|
||||
attempt, NordPoolConsts.MaxFetchRetryAttempts, label, date, delay);
|
||||
var todayNordPoolPrice = ParseNordPoolResult(element);
|
||||
|
||||
await Task.Delay(delay);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex,
|
||||
"Failed to fetch {Label} prices for {Date} on attempt {Attempt} with unexpected error", label, date,
|
||||
attempt);
|
||||
break;
|
||||
}
|
||||
|
||||
logger.LogWarning(
|
||||
"All {MaxAttempts} attempts to fetch {Label} prices for {Date} exhausted; returning empty prices",
|
||||
NordPoolConsts.MaxFetchRetryAttempts, label, date);
|
||||
|
||||
return new NordPoolPrice();
|
||||
}
|
||||
|
||||
private async Task<NordPoolPrice> GetNordPoolPriceAsync(DateOnly date)
|
||||
{
|
||||
var nordPoolPricesDto = await _nordPoolServices.GetPricesForDateAsync(
|
||||
new NordpoolGetPricesForDateParameters
|
||||
{
|
||||
Areas = "LT",
|
||||
ConfigEntry = NordPoolConsts.ConfigEntry,
|
||||
Currency = "EUR",
|
||||
Date = date
|
||||
});
|
||||
|
||||
var nordPoolResult = ParseNordPoolResult(nordPoolPricesDto);
|
||||
|
||||
return AdjustedNordPoolPrice(nordPoolResult);
|
||||
return AdjustedNordPoolPrice(todayNordPoolPrice);
|
||||
}
|
||||
|
||||
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
|
||||
{
|
||||
if (element == null) return new NordPoolPrice();
|
||||
if (!element.HasValue) return new NordPoolPrice();
|
||||
|
||||
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
|
||||
|
||||
@@ -207,4 +175,29 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
|
||||
return totalMinutes / NordPoolConsts.MinutesPerInterval;
|
||||
}
|
||||
|
||||
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
|
||||
{
|
||||
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
|
||||
try
|
||||
{
|
||||
return await fetchPricesForDate(date);
|
||||
}
|
||||
catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts)
|
||||
{
|
||||
var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1));
|
||||
logger.LogWarning(ex, "Attempt {Attempt}/{MaxAttempts} to fetch prices for {Date} failed. Retrying in {Delay}", attempt, NordPoolConsts.MaxFetchRetryAttempts, date, delay);
|
||||
|
||||
await Task.Delay(delay);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to fetch prices for {Date} on attempt {Attempt} with unexpected error", date, attempt);
|
||||
break;
|
||||
}
|
||||
|
||||
logger.LogWarning("All {MaxAttempts} attempts to fetch prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, date);
|
||||
|
||||
return new NordPoolPrice();
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,11 @@ public static class NordPoolServiceRegistration
|
||||
{
|
||||
services
|
||||
.AddNetDaemonApp<NordPoolInit>()
|
||||
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
|
||||
// Singleton is safe: NordPoolPriceService holds no IHaContext/generated
|
||||
// entity dependency. The HA price fetch call lives in NordPoolInit.
|
||||
.AddSingleton<INordPoolPriceService, NordPoolPriceService>()
|
||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
||||
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||
.AddTransient<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>();
|
||||
|
||||
return services;
|
||||
|
||||
Reference in New Issue
Block a user