fix(prediction): key cached provider requests on the settings they read

The file cache keyed provider request methods on their arguments and
code only. They take no arguments besides self and read location,
planes, tokens and past days from the configuration, so after a
configuration change they got the response for the previous one until
the 1-hour TTL expired, also across restarts.

cache_in_file takes an optional key_context, called with the arguments
of each call; a hash of its result is part of the key. Each provider
request declares the settings it is built from with
cache_request("general/latitude", ...), which builds the key context
from them. A change of other settings, e.g. an import value or a tariff
that an adapter pushes on every run, keeps the cache entry. The MD5
digest of the declared values is computed once per settings generation:
ConfigEOS.settings_generation() counts every _setup() (merge, reset,
revert, update) and every set_nested_value().

cache_in_file also takes key_context_hold: after a change of the key
context, a further change within the hold keeps using the valid entry
of the context in use. The first change, a change after the hold and a
forced update apply at once. A result is only stored under the context
it was computed for. cache_request passes its keyword arguments on to
cache_in_file; with_ttl defaults to REQUEST_CACHE_TTL (1 hour) and also
sets key_context_hold, so settings changes cause at most one extra
request per provider and TTL.

In a simulation of 6 hours of 5-minute runs with an import value pushed
on every run and four location and plane edits, the weather and PV
requests run 6 times (as on main), and every edit reaches the provider
within the hour.

Additional changes
Test that every cached request declares the settings it reads, including
those read by helper methods of its module
Test the settings generation counter, the reuse of the digest, the hold
and the cache_request defaults and pass-through
Add general/timezone to BrightSky (in the URL) and Forecast.Solar
(fallback zone of the response)
Clear the hold state with the whole file cache
Add a CHANGELOG entry

Refs: #1559
Signed-off-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
SchaafAlexander
2026-11-20 19:06:40 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent b944d4adfa
commit 3035ec0a4b
24 changed files with 691 additions and 36 deletions
+22 -1
View File
@@ -470,6 +470,8 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
_config_autosave: ClassVar[str] = ""
# Settings provided at runtime, e.g. by the REST interface. Highest priority after CLI.
_runtime_settings: ClassVar[dict[str, Any]] = {}
# Counts the setups and nested value changes, see `settings_generation()`.
_settings_generation: ClassVar[int] = 0
# A ClassVar: without the annotation pydantic makes it a private attribute,
# and the class attribute would be a (truthy) descriptor object.
_force_documentation_mode: ClassVar[bool] = False
@@ -813,6 +815,7 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
def _setup(self, *args: Any, **kwargs: Any) -> None:
"""Re-initialize global settings."""
logger.debug("Config setup with parameters {} {}", args, kwargs)
ConfigEOS._settings_generation += 1
# Assure settings base knows the singleton EOS configuration
SettingsBaseModel.config = self
@@ -849,6 +852,20 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
for message in warnings:
logger.warning(message)
@classmethod
def settings_generation(cls) -> int:
"""Number that changes whenever the settings may have changed.
It counts every setup of the settings (merge, reset, revert, update) and every
`set_nested_value()`. Use it to keep values derived from the settings until the
next change. A direct attribute assignment, e.g. ``config.general.latitude = 1.0``,
does not count.
Returns:
The current generation.
"""
return cls._settings_generation
def merge_settings(self, settings: SettingsEOS) -> None:
"""Merges the provided settings into the global settings for EOS, with optional overwrite.
@@ -906,7 +923,11 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
path (str): A '/'-separated path to the nested attribute (e.g. "server/port").
value (Any): The new value to set.
"""
super().set_nested_value(path, value)
try:
super().set_nested_value(path, value)
finally:
# Also after a partly applied change.
ConfigEOS._settings_generation += 1
# Remember as runtime setting to survive re-evaluation of the configuration sources.
# List indices can not be expressed by the settings dictionary - remember the whole list.
+114 -2
View File
@@ -5,6 +5,7 @@ both in memory (using an LRU cache) and in temporary files. It also includes
mechanisms for managing cache file expiration and retrieval.
"""
import contextlib
import functools
import hashlib
import inspect
@@ -816,6 +817,11 @@ class CacheFileStore(ConfigMixin, SingletonMixin):
Raises:
OSError: If there's an error during file deletion.
"""
if clear_all:
# Without entries there is nothing to hold (see `key_context_hold`).
# Suppressed: clear_all also runs on __del__, possibly at interpreter exit.
with contextlib.suppress(Exception), _key_context_lock:
_key_context_states.clear()
# Some weired logic to prevent calling to_datetime on clear_all.
# Clear_all may be set on __del__. At this time some info for to_datetime will
# not be available anymore.
@@ -963,6 +969,17 @@ class CacheFileStore(ConfigMixin, SingletonMixin):
return store_loaded
# `cache_in_file(key_context_hold=...)` state per argument key:
# (context hash in use, when it was switched to, last held context hash).
_key_context_states: dict[str, tuple[str, Optional[DateTime], Optional[str]]] = {}
_key_context_lock = threading.Lock()
def _hold_now() -> DateTime:
"""Current time for `cache_in_file(key_context_hold=...)`; tests replace it."""
return to_datetime()
def cache_in_file(
ignore_params: List[str] = [],
force_update: Optional[bool] = None,
@@ -972,6 +989,8 @@ def cache_in_file(
mode: Literal["w", "w+", "wb", "wb+", "r", "r+", "rb", "rb+"] = "wb+",
delete: bool = False,
suffix: Optional[str] = None,
key_context: Optional[Callable[..., Any]] = None,
key_context_hold: Optional[Any] = None,
) -> Callable[[Callable[Param, RetType]], Callable[Param, RetType]]:
"""Cache the output of a function into a temporary file.
@@ -1011,6 +1030,19 @@ def cache_in_file(
suffix (Optional[str], optional):
A file suffix (e.g., ".txt" or ".json") for the cache file. Defaults to None. If not
provided, files are pickled by default.
key_context (Optional[Callable[..., Any]], optional):
Called with the arguments of each call; a hash of the ``repr()`` of its result is
part of the cache key. Use it when the result depends on state the arguments do
not carry, e.g. a method that builds its request from the configuration of
``self``. Defaults to None.
key_context_hold (Union[timedelta, str, int, float, None], optional):
Limits how often a change of the `key_context` leads to a new call. After the
context of a call changed, a later change within this duration keeps using the
still valid cache entry of the current context instead of calling the function.
The first change, and any change once the duration passed, applies at once.
A forced update applies the change at once. Without a valid entry to keep, the
function is called for the new context. Defaults to None (every change applies
at once).
Returns:
Callable[[Callable[Param, RetType]], Callable[Param, RetType]]:
@@ -1029,8 +1061,10 @@ def cache_in_file(
Notes:
- The cache key is based on the function arguments after excluding those in
`ignore_params`, and on a hash of the function's code, defaults and captured
values (see `_get_func_code_hash`).
`ignore_params`, on a hash of the function's code, defaults and captured
values (see `_get_func_code_hash`), and on the `key_context`, if given.
- With `key_context_hold`, a cached result is only ever stored under the context it
was computed for; holding only reuses an existing entry.
- The control parameters (`force_update`, `until_date`, `until_datetime`,
`with_ttl`) are consumed by the wrapper and are not forwarded to the wrapped
function.
@@ -1044,6 +1078,55 @@ def cache_in_file(
func_code_hash = _get_func_code_hash(func)
# Follows functools.wraps wrappers to the signature of the wrapped function.
func_signature = inspect.signature(func)
hold = None if key_context_hold is None else to_duration(key_context_hold)
def held_context(base_key: str, context_hash: str, call_force_update: bool) -> str:
"""Return the context hash to try for this call, see `key_context_hold`.
The context in use is kept while its hold lasts; the caller falls back to
`switch_context` if it has no valid cache entry.
"""
with _key_context_lock:
state = _key_context_states.get(base_key)
if state is None:
if len(_key_context_states) >= 256:
_key_context_states.clear()
_key_context_states[base_key] = (context_hash, None, None)
return context_hash
active, switched_at, held = state
if context_hash == active:
if held is not None:
_key_context_states[base_key] = (active, switched_at, None)
return active
if (
not call_force_update
and hold is not None
and switched_at is not None
and _hold_now() < switched_at + hold
):
return active
_key_context_states[base_key] = (context_hash, _hold_now(), None)
return context_hash
def switch_context(base_key: str, context_hash: str) -> None:
"""Use `context_hash` from now on; its hold starts now."""
with _key_context_lock:
_key_context_states[base_key] = (context_hash, _hold_now(), None)
def report_held(base_key: str, context_hash: str) -> None:
"""Log once per change that a changed context waits for the hold to end."""
with _key_context_lock:
state = _key_context_states.get(base_key)
if state is None or state[2] == context_hash or state[1] is None:
return
_key_context_states[base_key] = (state[0], state[1], context_hash)
until = state[1] + hold # type: ignore[operator]
logger.info(
"{}: changed settings apply from {} on; the cached result of the previous "
"settings is used until then.",
func.__qualname__,
to_datetime(until, as_string=True),
)
def wrapper(*args: Param.args, **kwargs: Param.kwargs) -> RetType:
# Control parameters given at call time apply to this call only.
@@ -1073,6 +1156,17 @@ def cache_in_file(
# Create key based on argument names, argument values, and function code
key = str(_cache_key_arguments(func_signature, args, kwargs, ignore_params))
key += func_code_hash
base_key = key
context_hash = use_hash = ""
if key_context is not None:
# State outside the arguments that decides the result, e.g. the
# configuration a provider builds its request from.
context = repr(key_context(*args, **kwargs))
context_hash = hashlib.sha256(context.encode("utf-8")).hexdigest()
use_hash = context_hash
if hold is not None:
use_hash = held_context(base_key, context_hash, bool(call_force_update))
key = base_key + use_hash
result: Optional[RetType | bytes] = None
# Get cache file that is currently valid
@@ -1082,6 +1176,20 @@ def cache_in_file(
until_datetime=expiry["until_datetime"],
ttl_duration=expiry["with_ttl"],
)
if use_hash != context_hash:
if cache_file is None:
# Nothing to keep: call for the current context, never store the
# result under another one.
switch_context(base_key, context_hash)
key = base_key + context_hash
cache_file = CacheFileStore().get(
key,
until_date=expiry["until_date"],
until_datetime=expiry["until_datetime"],
ttl_duration=expiry["with_ttl"],
)
else:
report_held(base_key, context_hash)
if not call_force_update and cache_file is not None:
# cache file is available
try:
@@ -1095,6 +1203,10 @@ def cache_in_file(
logger.info(f"Read failed: {e}")
# Fail gracefully - recreate the cache file in this call
call_force_update = True
if use_hash != context_hash:
# Recreate it for the current context, not the held one.
switch_context(base_key, context_hash)
key = base_key + context_hash
if call_force_update or cache_file is None:
# Otherwise, call the function and save its result to the cache.
# Call first: a call that raises leaves no empty cache file behind.
@@ -14,9 +14,9 @@ from loguru import logger
from pydantic import ValidationError
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime, to_duration
@@ -90,7 +90,7 @@ class ElecPriceAkkudoktor(ElecPriceProvider):
raise ValueError(error_msg)
return akkudoktor_data
@cache_in_file(with_ttl="1 hour")
@cache_request("general/timezone", "prediction/hours")
def _request_forecast(self) -> AkkudoktorElecPrice:
"""Fetch electricity price forecast data from Akkudoktor API.
@@ -16,9 +16,9 @@ from loguru import logger
from pydantic import Field, ValidationError
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime, to_duration
@@ -171,7 +171,7 @@ class ElecPriceEnergyCharts(ElecPriceProvider):
return bidding_zone.value
return str(bidding_zone)
@cache_in_file(with_ttl="1 hour")
@cache_request("elecprice/energycharts", "prediction/hours")
def _request_forecast(self, start_date: Optional[str] = None) -> EnergyChartsElecPrice:
"""Fetch electricity price forecast data from Energy-Charts API.
@@ -9,12 +9,12 @@ from loguru import logger
from pydantic import Field, ValidationError
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.prediction.elecpriceenergycharts import (
ElecPriceEnergyCharts,
EnergyChartsElecPrice,
)
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
SMARD_BASE_URL = "https://www.smard.de/app/chart_data"
@@ -130,7 +130,7 @@ class ElecPriceSMARD(ElecPriceEnergyCharts):
selected.append(chunk_start)
return selected
@cache_in_file(with_ttl="1 hour")
@cache_request("elecprice/smard", "general/timezone", "prediction/hours")
def _request_forecast(self, start_date: Optional[str] = None) -> EnergyChartsElecPrice:
"""Fetch and normalize quarter-hourly German/Luxembourg day-ahead prices from SMARD."""
if not self.ems_start_datetime:
@@ -9,9 +9,9 @@ from loguru import logger
from pydantic import Field, ValidationError
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
TIBBER_GRAPHQL_URL = "https://api.tibber.com/v1-beta/gql"
@@ -217,7 +217,7 @@ class ElecPriceTibber(ElecPriceProvider):
tomorrow_count = len(subscription.priceInfo.tomorrow)
return history_count, today_count, tomorrow_count
@cache_in_file(with_ttl="1 hour")
@cache_request("elecprice/tibber/access_token")
def _request_forecast(self) -> TibberGraphQLResponse:
"""Fetch electricity price data from the Tibber GraphQL API."""
access_token = self.config.elecprice.tibber.access_token
@@ -10,12 +10,12 @@ import requests
from loguru import logger
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.elecpriceakkudoktor import (
AkkudoktorElecPrice,
ElecPriceAkkudoktor,
)
from akkudoktoreos.prediction.feedintariffabc import FeedInTariffProvider
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
@@ -51,7 +51,7 @@ class FeedInTariffAkkudoktor(FeedInTariffProvider):
"""Return the unique provider identifier."""
return "FeedInTariffAkkudoktor"
@cache_in_file(with_ttl="1 hour")
@cache_request("general/timezone", "prediction/hours")
def _request_forecast(self) -> AkkudoktorElecPrice:
"""Fetch market prices from the public Akkudoktor API."""
if not self.ems_start_datetime:
@@ -10,8 +10,8 @@ from loguru import logger
from pydantic import Field
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.feedintariffabc import FeedInTariffProvider
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
@@ -63,7 +63,7 @@ class FeedInTariffDvhubOnline(FeedInTariffProvider):
return FeedInTariffDvhubOnlineCommonSettings()
return settings
@cache_in_file(with_ttl="1 hour")
@cache_request("feedintariff/dvhubonline")
def _request_forecast(self, start_date: str, end_date: str) -> dict[str, Any]:
"""Fetch market prices from the dvhub.online price API."""
settings = self._provider_settings()
@@ -10,13 +10,13 @@ from loguru import logger
from pydantic import Field
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.elecpriceenergycharts import (
ElecPriceEnergyCharts,
EnergyChartsBiddingZones,
EnergyChartsElecPrice,
)
from akkudoktoreos.prediction.feedintariffabc import FeedInTariffProvider
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
@@ -108,7 +108,7 @@ class FeedInTariffEnergyCharts(FeedInTariffProvider):
return bidding_zone.value
return str(bidding_zone)
@cache_in_file(with_ttl="1 hour")
@cache_request("feedintariff/energycharts", "prediction/hours")
def _request_forecast(self, start_date: Optional[str] = None) -> EnergyChartsElecPrice:
"""Fetch electricity price forecast data from Energy-Charts API.
@@ -9,7 +9,6 @@ import requests
from loguru import logger
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.elecpricetibber import (
TIBBER_GRAPHQL_URL,
TIBBER_PRICE_QUERY_QUARTER_HOURLY,
@@ -18,6 +17,7 @@ from akkudoktoreos.prediction.elecpricetibber import (
TibberPricePoint,
)
from akkudoktoreos.prediction.feedintariffabc import FeedInTariffProvider
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
@@ -47,7 +47,7 @@ class FeedInTariffTibber(FeedInTariffProvider):
"""Keep enough history for seasonal price extrapolation."""
return 24 * 35
@cache_in_file(with_ttl="1 hour")
@cache_request("elecprice/tibber/access_token")
def _request_forecast(self) -> TibberGraphQLResponse:
"""Request strictly quarter-hourly Tibber prices.
+93 -1
View File
@@ -8,11 +8,15 @@ This module is designed for use in predictive modeling workflows, facilitating t
and manipulation of configuration and prediction data in a clear, scalable, and structured manner.
"""
from typing import Generic, List, Optional, TypeVar
import hashlib
import json
from typing import Any, Callable, Generic, List, Optional, TypeVar
from loguru import logger
from pydantic import Field, computed_field
from pydantic_core import to_jsonable_python
from akkudoktoreos.core.cache import Param, RetType, cache_in_file
from akkudoktoreos.core.coreabc import MeasurementMixin
from akkudoktoreos.core.dataabc import (
DataABC,
@@ -25,6 +29,94 @@ from akkudoktoreos.core.dataabc import (
)
from akkudoktoreos.utils.datetimeutil import DateTime, Duration, to_duration
# Default for how long a provider response stays cached, and the shortest time between
# two requests caused by settings changes (see `cache_request`).
REQUEST_CACHE_TTL = "1 hour"
def request_config_context(*config_paths: str) -> Callable[..., str]:
"""Build a cache key context from the settings a provider request is built from.
The returned function takes the provider (``self`` of the cached method) and returns
the MD5 digest of the values at ``config_paths`` (``'/'``-separated, as for
``get_nested_value``). The digest is kept until the settings change
(``ConfigEOS.settings_generation()``).
Args:
*config_paths: The settings the request reads, e.g. ``"general/latitude"``.
Returns:
The key context function for ``cache_in_file(key_context=...)``.
"""
if not config_paths:
raise ValueError("A request cache context needs at least one configuration path.")
paths = tuple(config_paths)
# (config id, settings generation, digest) of the last result.
last: list[Optional[tuple[int, int, str]]] = [None]
def context(provider: Any, *args: Any, **kwargs: Any) -> str:
config = provider.config
generation = config.settings_generation()
cached = last[0]
if cached is not None and cached[0] == id(config) and cached[1] == generation:
return cached[2]
values = {path: to_jsonable_python(config.get_nested_value(path)) for path in paths}
text = json.dumps(values, sort_keys=True, default=str)
digest = hashlib.md5(text.encode("utf-8"), usedforsecurity=False).hexdigest()
last[0] = (id(config), generation, digest)
return digest
context.config_paths = paths # type: ignore[attr-defined]
return context
def cache_request(
*config_paths: str,
**cache_kwargs: Any,
) -> Callable[[Callable[Param, RetType]], Callable[Param, RetType]]:
"""Cache a provider request in a file, keyed on the settings it is built from (#1559).
Provider request methods read their parameters (location, planes, tokens, past days)
from the configuration, not from their arguments. The values at ``config_paths`` are
part of the cache key, so a change of them requests new data instead of reusing the
response for the previous settings. Other settings changes leave the cache alone.
To protect the provider rate limits, settings changes lead to at most one extra request
per ``with_ttl``: a further change within that time keeps the cached response until
then (``cache_in_file(key_context_hold=...)``). A forced update applies it at once.
Example:
.. code-block:: python
@cache_request("general/latitude", "general/longitude")
def _request_forecast(self) -> dict: ...
# A provider with a stricter rate limit: cache and hold for 3 hours.
@cache_request("pvforecast/planes", with_ttl="3 hours")
def _request_forecast(self) -> dict: ...
Args:
*config_paths: Every setting the request reads, as ``'/'``-separated paths.
They build the ``key_context``.
**cache_kwargs: Passed on to ``cache_in_file``. ``with_ttl`` defaults to
``REQUEST_CACHE_TTL``, and ``key_context_hold`` defaults to ``with_ttl``.
Returns:
The ``cache_in_file`` decorator.
"""
if "key_context" in cache_kwargs:
raise TypeError("cache_request builds the key_context from the config_paths.")
with_ttl = cache_kwargs.pop("with_ttl", None)
if with_ttl is None:
with_ttl = REQUEST_CACHE_TTL
key_context_hold = cache_kwargs.pop("key_context_hold", with_ttl)
return cache_in_file(
with_ttl=with_ttl,
key_context=request_config_context(*config_paths),
key_context_hold=key_context_hold,
**cache_kwargs,
)
class PredictionABC(DataABC, MeasurementMixin):
"""Base class for handling prediction data.
@@ -84,8 +84,8 @@ import requests
from loguru import logger
from pydantic import Field, ValidationError, computed_field, field_validator
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.prediction.pvforecast import PVForecastPlaneSetting
from akkudoktoreos.prediction.pvforecastabc import PVForecastDataRecord
from akkudoktoreos.prediction.pvforecastakkudoktorlocal import PVForecastAkkudoktorLocal
@@ -317,7 +317,7 @@ class PVForecastAkkudoktor(PVForecastAkkudoktorLocal[PVForecastAkkudoktorDataRec
return url
@cache_in_file(with_ttl="1 hour")
@cache_request("general/latitude", "general/longitude", "general/timezone", "pvforecast/planes")
def _request_forecast(self) -> AkkudoktorForecast:
"""Fetch PV forecast data from Akkudoktor API.
@@ -44,8 +44,8 @@ from loguru import logger
from pydantic import Field, PrivateAttr, field_validator, model_validator
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.measurement.measurement import MeterPeriod
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.prediction.pvforecastabc import (
PVForecastDataRecordT,
PVForecastProvider,
@@ -626,7 +626,13 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
return forecast_days, min(MAX_PAST_DAYS, past_days)
@cache_in_file(with_ttl="1 hour")
@cache_request(
"general/latitude",
"general/longitude",
"prediction/hours",
"prediction/historic_hours",
"pvforecast/akkudoktor",
)
def _request_local_forecast(self) -> Any:
"""Fetch raw irradiance and weather from Open-Meteo."""
latitude = self.config.general.latitude
@@ -29,7 +29,7 @@ from loguru import logger
from pydantic import Field
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.prediction.pvforecastabc import PVForecastProvider
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
@@ -157,7 +157,13 @@ class PVForecastForecastSolar(PVForecastProvider):
base = f"{base}/{api_key}"
return f"{base}/estimate/{latitude}/{longitude}/{float(tilt)}/{fs_az}/{float(peakpower)}"
@cache_in_file(with_ttl="1 hour")
@cache_request(
"general/latitude",
"general/longitude",
"general/timezone",
"pvforecast/planes",
"pvforecast/forecastsolar",
)
def _request_forecast(self) -> dict:
"""Fetch and aggregate the Forecast.Solar estimate across all configured planes."""
planes = self.config.pvforecast.planes or []
@@ -30,7 +30,7 @@ from loguru import logger
from pydantic import Field
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.prediction.pvforecastabc import PVForecastProvider
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -154,7 +154,12 @@ class PVForecastPVNode(PVForecastProvider):
rows.append((date, round(power, 1)))
return rows
@cache_in_file(with_ttl="1 hour")
@cache_request(
"general/latitude",
"general/longitude",
"pvforecast/planes",
"pvforecast/pvnode",
)
def _request_forecast(self) -> Any:
"""Fetch the PV forecast from pvnode.com (saved site or inline planes)."""
settings = self._settings
@@ -25,7 +25,7 @@ from loguru import logger
from pydantic import Field
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.prediction.pvforecastabc import PVForecastProvider
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -78,7 +78,7 @@ class PVForecastSolcast(PVForecastProvider):
minutes = int(match.group(2) or 0)
return hours * 60 + minutes
@cache_in_file(with_ttl="1 hour")
@cache_request("pvforecast/solcast")
def _request_forecast(self) -> Any:
"""Fetch the rooftop-site forecast from Solcast."""
settings = self._settings
@@ -14,7 +14,7 @@ import pandas as pd
import requests
from loguru import logger
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.prediction.weatherabc import WeatherDataRecord, WeatherProvider
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
@@ -78,7 +78,7 @@ class WeatherBrightSky(WeatherProvider):
"""Return the unique identifier for the BrightSky provider."""
return "BrightSky"
@cache_in_file(with_ttl="1 hour")
@cache_request("general/latitude", "general/longitude", "general/timezone", "prediction/hours")
def _request_forecast(self) -> dict:
"""Fetch weather forecast data from BrightSky API.
@@ -19,7 +19,7 @@ import pandas as pd
import requests
from loguru import logger
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.prediction.weatherabc import WeatherDataRecord, WeatherProvider
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_timezone
@@ -79,7 +79,7 @@ class WeatherClearOutside(WeatherProvider):
def provider_id(cls) -> str:
return "ClearOutside"
@cache_in_file(with_ttl="1 hour")
@cache_request("general/latitude", "general/longitude")
def _request_forecast(self) -> requests.Response:
"""Requests weather forecast from ClearOutside.
@@ -13,7 +13,7 @@ import pandas as pd
import requests
from loguru import logger
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.prediction.predictionabc import cache_request
from akkudoktoreos.prediction.weatherabc import WeatherDataRecord, WeatherProvider
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
@@ -109,7 +109,7 @@ class WeatherOpenMeteo(WeatherProvider):
"""Return the unique identifier for the Open-Meteo provider."""
return "OpenMeteo"
@cache_in_file(with_ttl="1 hour")
@cache_request("general/latitude", "general/longitude", "general/timezone", "prediction/hours")
def _request_forecast(self) -> dict:
"""Fetch weather forecast data from Open-Meteo API.