refactor: make StateCache descriptor-free

This commit is contained in:
Marc Billow committed 2026-06-30 16:32:37 -05:00
1 parent f2c1d8391e
commit 35222e6be5
2 files changed
+22 -7

No files matched your search

+7 -7
View File
@@ -8,26 +8,26 @@ from __future__ import annotations
import threading import threading
import time import time
from typing import Callable, Optional, TYPE_CHECKING from typing import Callable, Optional
if TYPE_CHECKING:
from .appliances.base import ApplianceDescriptor
class StateCache: class StateCache:
def __init__(self, descriptor: 'ApplianceDescriptor'): def __init__(self):
self.descriptor = descriptor
self.links: dict[str, dict] = {} self.links: dict[str, dict] = {}
self.last_updated: dict[str, float] = {} self.last_updated: dict[str, float] = {}
self.source: dict[str, str] = {} self.source: dict[str, str] = {}
self.descriptor_state: dict = {} self.descriptor_state: dict = {}
self._on_change: Optional[Callable[[bool, str], None]] = None self._on_change: Optional[Callable[[bool, str], None]] = None
self._on_observation: Optional[Callable[[dict, str, dict], None]] = None
self._lock = threading.RLock() self._lock = threading.RLock()
def set_on_change(self, cb: Callable[[bool, str], None]) -> None: def set_on_change(self, cb: Callable[[bool, str], None]) -> None:
self._on_change = cb self._on_change = cb
def set_on_observation(self, hook: Optional[Callable[[dict, str, dict], None]]) -> None:
self._on_observation = hook
def apply_rep(self, href: str, rep: dict, source: str) -> bool: def apply_rep(self, href: str, rep: dict, source: str) -> bool:
if not isinstance(rep, dict): if not isinstance(rep, dict):
return False return False
@@ -37,7 +37,7 @@ class StateCache:
self.links[href] = rep self.links[href] = rep
self.last_updated[href] = time.time() self.last_updated[href] = time.time()
self.source[href] = source self.source[href] = source
hook = self.descriptor.on_observation hook = self._on_observation
if hook is not None: if hook is not None:
try: try:
hook(self.descriptor_state, href, rep) hook(self.descriptor_state, href, rep)
+15
View File
@@ -0,0 +1,15 @@
from samsung_appliance.state_cache import StateCache
def test_state_cache_constructs_without_descriptor():
c = StateCache()
assert c.links == {}
assert c.descriptor_state == {}
def test_on_observation_hook_fires():
c = StateCache()
seen = []
c.set_on_observation(lambda st, href, rep: seen.append((href, rep)))
c.apply_rep('/x/vs/0', {'a': 1}, source='seed')
assert seen == [('/x/vs/0', {'a': 1})]