fix: move data management to async (#1015)

FAstAPI is an async framework. Data may be imported and exported, load and save, set and get
asynchronously. Prevent interleaving data operations to corrupt the data. In the previous design
sync and async data access was intermixed leading to data corruption.

The basic data classes DataSequence and DataContainer and the derived classes like Provider and
Measurement now are async. Data access is protected by several async locks.

To support the async design of the data classes the database interface became async.

The energy management is also adapted to the new async design. Optimization is still off-loaded
to another thread, but the prepration for the optimization and the post optimization actions now
follow the async design.

Adapter operations are now also protected by async locks.

Tests were adapted to the async design and new tests were created.

Besides this major fix several other improvements and fixes are included in this PR.

* fix: key_to_dict/list/array only regard data records with key value set.

  Before the exclusion of no value data records was only done if the dropna flag was set.

* fix: test for visual result pdf generation

  Due to updates in the library the generated charts text was a little bit different.
  Adapt the test to create the comaprison pdf in the test data durectory and
  update the reference pdf.

* chore: Remove MutableMapping from DataSequence and DataContainer.

  Mutable Mapping does not fit to the now async design.

* chore: Add NoDB database backend

  This backend implements the full database backend interface but performs
  no actual persistence. It is intended for configurations where database
  persistence is disabled (`provider=None`).

* chore: Improve measurement data import testing with real world scenarios.

  Added two new endpoints to support testing.

* chore: Add mermaid to supported documentation tools

* chore: Add documentation about async design

* chore: Add documentation about generic data handling

  Covers the basics of measurement and prediction time series data handling.

* chore: Add empty lines around markdown lists.

* chore: sync pre-commit config to updated package versions

Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
This commit is contained in:
Bobby Noelte
2026-07-15 16:38:53 +02:00
committed by GitHub
parent 38011780c5
commit eb9e966de9
99 changed files with 11971 additions and 5981 deletions
+40 -7
View File
@@ -1,5 +1,6 @@
"""Abstract and base classes for adapters."""
import asyncio
from abc import abstractmethod
from typing import Any, Optional
@@ -53,12 +54,27 @@ class AdapterProvider(SingletonMixin, ConfigMixin, MeasurementMixin, StartMixin,
return self.provider_id() in self.config.adapter.provider
return False
@property
def _adapter_lock(self) -> asyncio.Lock:
"""Per-instance asyncio lock guarding adapter-level bulk operations.
The lock guards the full adapter state during bulk operations.
"""
try:
return object.__getattribute__(self, "_adapter_lock_instance")
except AttributeError:
lock = asyncio.Lock()
object.__setattr__(self, "_adapter_lock_instance", lock)
return lock
@abstractmethod
def _update_data(self) -> None:
async def _update_data(self) -> None:
"""Abstract method for custom adapter data update logic, to be implemented by derived classes.
Data update may be requested at different stages of energy management. The stage can be
detected by self.ems.stage().
This method is always called while `_adapter_lock` is held by the caller.
"""
pass
@@ -67,7 +83,7 @@ class AdapterProvider(SingletonMixin, ConfigMixin, MeasurementMixin, StartMixin,
return
super().__init__(*args, **kwargs)
def update_data(
async def update_data(
self,
force_enable: Optional[bool] = False,
) -> None:
@@ -81,8 +97,9 @@ class AdapterProvider(SingletonMixin, ConfigMixin, MeasurementMixin, StartMixin,
return
# Call the custom update logic
logger.debug(f"Update adapter provider: {self.provider_id()}")
self._update_data()
async with self._adapter_lock:
logger.debug(f"Update adapter provider: {self.provider_id()}")
await self._update_data()
class AdapterContainer(SingletonMixin, ConfigMixin, PydanticBaseModel):
@@ -105,6 +122,19 @@ class AdapterContainer(SingletonMixin, ConfigMixin, PydanticBaseModel):
)
return value
@property
def _container_lock(self) -> asyncio.Lock:
"""Coarse-grained lock for bulk operations across providers.
The lock guards cross-provider consistency during container operations.
"""
try:
return object.__getattribute__(self, "_container_lock_instance")
except AttributeError:
lock = asyncio.Lock()
object.__setattr__(self, "_container_lock_instance", lock)
return lock
@property
def enabled_providers(self) -> list[Any]:
"""List of providers that are currently enabled."""
@@ -145,7 +175,7 @@ class AdapterContainer(SingletonMixin, ConfigMixin, PydanticBaseModel):
raise ValueError(error_msg)
return providers[provider_id]
def update_data(
async def update_data(
self,
force_enable: Optional[bool] = False,
) -> None:
@@ -154,7 +184,10 @@ class AdapterContainer(SingletonMixin, ConfigMixin, PydanticBaseModel):
Args:
force_enable (bool, optional): If True, forces the update even if the provider is disabled.
"""
if len(self.providers) <= 0:
return
# Call the custom update logic
if len(self.providers) > 0:
async with self._container_lock:
for provider in self.providers:
provider.update_data(force_enable=force_enable)
await provider.update_data(force_enable=force_enable)
+6 -6
View File
@@ -419,7 +419,7 @@ class HomeAssistantAdapter(AdapterProvider):
# Preserve original state for enums and free-text states
return raw_state
def _update_data(self) -> None:
async def _update_data(self) -> None:
stage = self.ems.stage()
if stage == EnergyManagementStage.DATA_ACQUISITION:
# Sync configuration
@@ -451,7 +451,7 @@ class HomeAssistantAdapter(AdapterProvider):
logger.debug(f"Entity {entity_id}: {state}")
if state:
measurement_value = float(state)
self.measurement.update_value(
await self.measurement.update_value(
self.ems_start_datetime, measurement_key, measurement_value
)
except Exception as e:
@@ -473,7 +473,7 @@ class HomeAssistantAdapter(AdapterProvider):
logger.debug(f"Entity {entity_id}: {state}")
if state:
measurement_value = float(state)
self.measurement.update_value(
await self.measurement.update_value(
self.ems_start_datetime, measurement_key, measurement_value
)
except Exception as e:
@@ -495,7 +495,7 @@ class HomeAssistantAdapter(AdapterProvider):
logger.debug(f"Entity {entity_id}: {state}")
if state:
measurement_value = float(state)
self.measurement.update_value(
await self.measurement.update_value(
self.ems_start_datetime, measurement_key, measurement_value
)
except Exception as e:
@@ -517,7 +517,7 @@ class HomeAssistantAdapter(AdapterProvider):
logger.debug(f"Entity {entity_id}: {state}")
if state:
measurement_value = float(state)
self.measurement.update_value(
await self.measurement.update_value(
self.ems_start_datetime, measurement_key, measurement_value
)
except Exception as e:
@@ -539,7 +539,7 @@ class HomeAssistantAdapter(AdapterProvider):
logger.debug(f"Entity {entity_id}: {state}")
if state:
measurement_value = float(state)
self.measurement.update_value(
await self.measurement.update_value(
self.ems_start_datetime, measurement_key, measurement_value
)
except Exception as e:
+1 -1
View File
@@ -66,7 +66,7 @@ class NodeREDAdapter(AdapterProvider):
"""Return the unique identifier for the adapter provider."""
return "NodeRED"
def _update_data(self) -> None:
async def _update_data(self) -> None:
"""Custom adapter data update logic.
Data update may be requested at different stages of energy management. The stage can be