diff --git a/meshterm/context.py b/meshterm/context.py index c7c09ac..709244e 100644 --- a/meshterm/context.py +++ b/meshterm/context.py @@ -33,6 +33,7 @@ if TYPE_CHECKING: from .services.monitor_service import MonitorService from .services.watchtower import WatchtowerService from .services.battery_service import BatteryService + from .services.device_state import DeviceState from .ui.surface import Ui @@ -105,6 +106,7 @@ class AppContext: _watchtower: "Optional[WatchtowerService]" = field(default=None, init=False, repr=False) _courier: "Optional[CourierService]" = field(default=None, init=False, repr=False) _battery: "Optional[BatteryService]" = field(default=None, init=False, repr=False) + _devstate: "Optional[DeviceState]" = field(default=None, init=False, repr=False) _ui: "Optional[Ui]" = field(default=None, init=False, repr=False) def __post_init__(self) -> None: @@ -301,6 +303,21 @@ class AppContext: self._battery = BatteryService(self) return self._battery + @property + def devstate(self) -> "DeviceState": + """Return the session's device-state cache, creating it on first use. + + Holds the stable facts screens read from the companion on open (contacts, self-info, + path-hash mode, channel slots) so navigation doesn't re-read them from the radio every + time — the chief cause of slow screen transitions over Bluetooth. Created idle here; + each getter fetches lazily. Cleared on a reconnect (see :meth:`reconnect`). + """ + if self._devstate is None: + from .services.device_state import DeviceState + + self._devstate = DeviceState(self) + return self._devstate + @property def log(self): # type: ignore[no-untyped-def] """The application logger.""" @@ -479,6 +496,11 @@ class AppContext: pass self._device = None + # Facts cached against the connection that just dropped may be stale on the fresh link + # (a reboot could have changed the identity or config), so re-read them on next use. + if self._devstate is not None: + self._devstate.reset() + # Open a fresh connection (raises if the device still can't be reached, leaving the # remembered intent in place for the next attempt), then restart whatever was running # before it dropped and clear the intent now that we're back. @@ -514,6 +536,8 @@ class AppContext: async def aclose(self) -> None: """Stop monitoring and chat, stop the event hub, disconnect, and close the repo.""" + if self._devstate is not None: + await self._devstate.aclose() if self._courier is not None: await self._courier.aclose() if self._battery is not None: diff --git a/meshterm/services/device_state.py b/meshterm/services/device_state.py new file mode 100644 index 0000000..b3d344a --- /dev/null +++ b/meshterm/services/device_state.py @@ -0,0 +1,241 @@ +"""The session's device-state cache: read the radio once, reuse it everywhere. + +Opening a screen used to re-read the same stable facts from the companion every time — +the contacts table, the node's own self-info, the path-hash routing width, the configured +channel slots. Over Bluetooth each of those is a full request→reply round-trip, and the two +big ones dominate: ``get_contacts`` on a busy node (hundreds of contacts) and the channel +probe (:func:`~meshterm.ui.channels.read_channel_slots`, which walks every slot index) each +measured in *seconds* on real hardware. Firing them on every navigation is what made moving +between screens feel like it stalled. + +None of that data actually changes mid-navigation: + +* **self-info** and **path-hash mode** change only when the config editor writes them; +* **channel slots** change only when the channel editor saves one; +* **contacts** grow as the mesh advertises, but a minute-stale list is harmless — the app + already resolves names from recorded history too. + +So this service reads each fact once, holds it for the session, and hands screens the cached +copy instantly. The two rules that keep the cache honest: + +* **Contacts** use *stale-while-revalidate*: a read past :data:`_CONTACTS_TTL_S` returns the + cached list immediately and refreshes it in the background, so navigation is never blocked + on the slow call, yet newly-heard contacts still appear within a TTL of the next screen. +* Everything else is held until an in-app write **invalidates** it (see + :meth:`invalidate_self_info`, :meth:`invalidate_channels`, …); the writer is the only thing + that can change it, so it is also the only thing that needs to drop the cache. + +The cache is transport-agnostic — it sits above :meth:`~meshterm.context.AppContext.device`, +so serial sessions get the same win (smaller, since serial round-trips are faster) and the +``--mock`` simulator is simply always fast. It is cleared wholesale on a reconnect (see +:meth:`reset`), since a fresh link should re-read the truth. +""" + +from __future__ import annotations + +import asyncio +import time +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: + from ..core.models import Contact + from ..context import AppContext + from ..ui.channels import ChannelSlot + +#: How long a cached contacts list is served before a read triggers a background refresh +#: (seconds). Contacts only grow as the mesh advertises, and the list is a naming/addressing +#: convenience the app also fills from recorded history — so a slightly stale copy costs +#: nothing, while re-reading the (slow) table on every screen open cost seconds. A read past +#: this age still returns instantly from cache; the refresh happens behind it. +_CONTACTS_TTL_S = 90.0 + + +class DeviceState: + """Session-scoped cache of the stable facts screens read from the companion on open. + + Held on the :class:`~meshterm.context.AppContext` as ``ctx.devstate`` and created idle; + each getter fetches from the device on first use (opening the connection via + :meth:`AppContext.device` if needed) and serves the cached value thereafter. The getters + mirror the contract of the underlying :class:`~meshterm.core.connection.Device` methods — + :meth:`contacts` and :meth:`self_info` raise on a failed first fetch (their callers either + handle it or let it surface), :meth:`path_hash_mode` likewise so its optional-read callers + can fall back — so a call site can swap ``device.get_x()`` for ``ctx.devstate.x()`` without + changing how it handles failure. + """ + + def __init__(self, ctx: "AppContext") -> None: + """Initialize an empty cache bound to an application context. + + Args: + ctx: The shared application context, used to reach the device and to log. No + device is opened until a getter is first called. + """ + self._ctx = ctx + self._contacts: Optional[list["Contact"]] = None + self._contacts_at: float = 0.0 + self._self_info: Optional[dict] = None + self._path_hash_mode: Optional[int] = None + self._channels: Optional[list["ChannelSlot"]] = None + # One lock per slow fetch so overlapping first-access callers (two screens opened in + # quick succession) collapse onto a single round-trip instead of each firing their own. + self._contacts_lock = asyncio.Lock() + self._self_info_lock = asyncio.Lock() + self._channels_lock = asyncio.Lock() + self._tasks: set[asyncio.Task] = set() + + # -- contacts (stale-while-revalidate) -------------------------------------- + + async def contacts(self, *, force: bool = False) -> list["Contact"]: + """Return the device's contacts, cached for the session and refreshed lazily. + + The first call reads the table from the radio (a slow round-trip on a busy node) and + holds it. Later calls return the cached list *immediately*; once it is older than + :data:`_CONTACTS_TTL_S` a read also kicks off a background refresh, so the list stays + current without ever blocking navigation on the slow call. + + Args: + force: Re-read from the device now (blocking), bypassing the cache — for the rare + caller that needs the freshest possible list. + + Returns: + The device's contacts. Raises like + :meth:`~meshterm.core.connection.Device.get_contacts` if the *first* fetch fails + (a background refresh failure is swallowed, leaving the last good list in place). + """ + if force: + return await self._fetch_contacts(force=True) + if self._contacts is None: + return await self._fetch_contacts() + if time.monotonic() - self._contacts_at > _CONTACTS_TTL_S: + self._spawn(self._refresh_contacts_quietly()) + return self._contacts + + async def _fetch_contacts(self, *, force: bool = False) -> list["Contact"]: + """Read the contacts table from the device and cache it (blocking, deduplicated). + + Args: + force: Fetch unconditionally. When ``False``, a caller that refreshed the cache + while this one waited for the lock reuses that fresh result rather than issuing + a second identical round-trip. + """ + async with self._contacts_lock: + if not force and self._contacts is not None and ( + time.monotonic() - self._contacts_at <= _CONTACTS_TTL_S + ): + return self._contacts + device = await self._ctx.device() + self._contacts = await device.get_contacts() + self._contacts_at = time.monotonic() + return self._contacts + + async def _refresh_contacts_quietly(self) -> None: + """Background contacts refresh: update the cache, swallow a failure (keep the old list).""" + try: + await self._fetch_contacts() + except Exception as exc: # noqa: BLE001 - a stale list is fine; never surface here + self._ctx.log.debug("devstate: background contacts refresh failed: %s", exc) + + # -- self-info (held until an in-app write invalidates it) ------------------ + + async def self_info(self) -> dict: + """Return the node's own self-info, cached until the config editor invalidates it. + + Returns: + The self-info payload (identity, radio tuning, coordinates, tx power). Raises like + :meth:`~meshterm.core.connection.Device.get_self_info` if the fetch fails; the + failure is not cached, so the next call retries. + """ + if self._self_info is None: + async with self._self_info_lock: + if self._self_info is None: + device = await self._ctx.device() + self._self_info = dict(await device.get_self_info()) + return self._self_info + + async def path_hash_mode(self) -> int: + """Return the device's path-hash routing mode, cached for the session. + + Returns: + The path-hash mode integer. Raises like + :meth:`~meshterm.core.connection.Device.get_path_hash_mode` if the read fails, so + the optional-read callers that wrap this in ``try`` fall back exactly as before. + """ + if self._path_hash_mode is None: + device = await self._ctx.device() + self._path_hash_mode = int(await device.get_path_hash_mode()) + return self._path_hash_mode + + # -- channel slots (held until the channel editor invalidates them) -------- + + async def channel_slots(self) -> list["ChannelSlot"]: + """Return the configured channel slots, cached until a channel edit invalidates them. + + The underlying probe (:func:`~meshterm.ui.channels.read_channel_slots`) walks every + slot index on the firmware, which is one of the slowest reads on a screen open — so it + is well worth reading once. It is best-effort itself (an unsupported firmware yields an + empty list rather than raising), and that result is cached as-is. + + Returns: + One :class:`~meshterm.ui.channels.ChannelSlot` per configured slot, in index order. + """ + if self._channels is None: + async with self._channels_lock: + if self._channels is None: + from ..ui.channels import read_channel_slots + + device = await self._ctx.device() + self._channels = await read_channel_slots(device) + return self._channels + + # -- invalidation (called by the code that writes device state) ------------ + + def invalidate_contacts(self) -> None: + """Drop the cached contacts so the next read re-fetches (e.g. a contact was removed).""" + self._contacts = None + self._contacts_at = 0.0 + + def invalidate_self_info(self) -> None: + """Drop the cached self-info — call after writing name/coords/radio/tx power/tuning.""" + self._self_info = None + + def invalidate_path_hash_mode(self) -> None: + """Drop the cached path-hash mode — call after writing it in the config editor.""" + self._path_hash_mode = None + + def invalidate_channels(self) -> None: + """Drop the cached channel slots — call after the channel editor saves or clears one.""" + self._channels = None + + def invalidate_config(self) -> None: + """Drop everything the config editor can change in one call (self-info + routing mode). + + A convenience for the config editor's apply path, which may have written any of the + self-info fields and/or the path-hash mode; dropping both is cheaper than tracking + exactly which settings changed. + """ + self.invalidate_self_info() + self.invalidate_path_hash_mode() + + def reset(self) -> None: + """Clear the whole cache and cancel any in-flight background refresh. + + Called on a reconnect: a fresh link should re-read the truth rather than trust facts + cached against the connection that just dropped. + """ + self.invalidate_contacts() + self.invalidate_self_info() + self.invalidate_path_hash_mode() + self.invalidate_channels() + for task in list(self._tasks): + task.cancel() + self._tasks.clear() + + async def aclose(self) -> None: + """Cancel any background refresh at session end (an alias for :meth:`reset`).""" + self.reset() + + def _spawn(self, coro) -> None: # type: ignore[no-untyped-def] + """Run a background refresh as a tracked task so it can be cancelled on reset.""" + task = asyncio.ensure_future(coro) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) diff --git a/meshterm/tools/config.py b/meshterm/tools/config.py index 971f818..1e9e1c7 100644 --- a/meshterm/tools/config.py +++ b/meshterm/tools/config.py @@ -285,6 +285,18 @@ async def apply_ops( ctx.ui.note("[err]device factory-reset[/err]") else: # pragma: no cover - guarded by the call sites that build ops ctx.ui.note(f"[err]unknown config op: {kind}[/err]") + # Drop any session-cached facts these ops may have changed, so the next screen re-reads + # the truth rather than a stale copy (see meshterm.services.device_state.DeviceState). A + # reboot/reconnect resets the whole cache on its own; these cover the in-place edits. + kinds = {op[0] for op in ops} + _WHOLESALE = {"restore", "import_key", "factory_reset"} + if kinds & _WHOLESALE: + ctx.devstate.reset() + else: + if "set" in kinds: + ctx.devstate.invalidate_config() # self-info fields + path-hash mode + if "set_channel" in kinds: + ctx.devstate.invalidate_channels() return changes, artifacts diff --git a/meshterm/tools/map.py b/meshterm/tools/map.py index d678600..87c0b25 100644 --- a/meshterm/tools/map.py +++ b/meshterm/tools/map.py @@ -233,7 +233,7 @@ async def gather_markers(ctx: AppContext) -> list["MapMarker"]: async def _contacts(ctx: AppContext) -> list: """Fetch the device's contacts, best-effort (an unreachable radio yields none).""" try: - return await (await ctx.device()).get_contacts() + return await ctx.devstate.contacts() except Exception: # noqa: BLE001 - the map still works from observations alone return [] @@ -243,7 +243,7 @@ async def _self_marker(ctx: AppContext) -> Optional["MapMarker"]: from ..ui.map_render import MapMarker try: - info = await (await ctx.device()).get_self_info() + info = await ctx.devstate.self_info() except Exception: # noqa: BLE001 - the map is useful without our own position return None lat, lon = _as_float(info.get("adv_lat")), _as_float(info.get("adv_lon")) diff --git a/meshterm/tools/nodes.py b/meshterm/tools/nodes.py index 7c2de3e..22228bb 100644 --- a/meshterm/tools/nodes.py +++ b/meshterm/tools/nodes.py @@ -34,15 +34,18 @@ class NodesTool(Tool): from ..ui.surface import TuiUi from ..ui.widgets import NodesSort, nodes_table - device = await ctx.device() - info = await device.get_self_info() - contacts = await device.get_contacts() + # Read through the session cache: on a busy node the contacts table is a slow + # round-trip, and re-fetching it (plus self-info) on every menu visit is a chief cause + # of sluggish navigation. The cache holds them for the session and refreshes contacts + # in the background (see :class:`~meshterm.services.device_state.DeviceState`). + info = await ctx.devstate.self_info() + contacts = await ctx.devstate.contacts() # The path-hash prefix — the leading slice of a key a forced path addresses — is # ``mode + 1`` bytes wide; highlight it in every key. The mode is an optional read, # so fall back to no highlighting when the firmware doesn't report it. try: - mode = await device.get_path_hash_mode() + mode = await ctx.devstate.path_hash_mode() except Exception: # noqa: BLE001 - optional read; absence just skips highlighting mode = None prefix_bytes = (mode + 1) if isinstance(mode, int) and 0 <= mode <= 3 else 0 diff --git a/meshterm/ui/atlas_screen.py b/meshterm/ui/atlas_screen.py index 1772a4b..fe5f838 100644 --- a/meshterm/ui/atlas_screen.py +++ b/meshterm/ui/atlas_screen.py @@ -866,9 +866,8 @@ async def open_atlas(ctx: "AppContext") -> None: self_hash: Optional[str] = None try: if ctx.is_connected or ctx.settings.connect_on_start: - device = await ctx.device() - contacts = await device.get_contacts() - info = await device.get_self_info() + contacts = await ctx.devstate.contacts() + info = await ctx.devstate.self_info() self_label = str(info.get("name") or "you") self_hash = str(info.get("public_key") or "") or None except Exception: # noqa: BLE001 - names are a nicety; the graph renders without them diff --git a/meshterm/ui/channels.py b/meshterm/ui/channels.py index 2e928b3..98d72c3 100644 --- a/meshterm/ui/channels.py +++ b/meshterm/ui/channels.py @@ -177,11 +177,14 @@ async def manage_channels(ctx: "AppContext") -> int: if slot is not None: changes += await _channel_detail(ctx, device, slot, stats) if changes > before: - # A slot's occupant changed (created, re-keyed, cleared, or moved). Inbound - # messages carry only a slot index, which the chat service maps to a channel - # identity through a cache keyed by slot; refresh it now so a message on a - # reused/re-keyed slot is filed under the channel that's actually there and - # not the one that used to be — otherwise its transcript surfaces in the + # A slot's occupant changed (created, re-keyed, cleared, or moved). Drop the + # session cache's channel list so the dashboard (and anything else reading it) + # re-reads the new layout instead of a stale copy. + ctx.devstate.invalidate_channels() + # Inbound messages carry only a slot index, which the chat service maps to a + # channel identity through a cache keyed by slot; refresh it now so a message + # on a reused/re-keyed slot is filed under the channel that's actually there + # and not the one that used to be — otherwise its transcript surfaces in the # wrong chat. await _refresh_chat_channels(ctx) return True diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index 499408c..d9f2e60 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -781,7 +781,7 @@ async def open_chat(ctx: "AppContext", conversation: Conversation) -> int: peer=conversation.peer, limit=_HISTORY_LIMIT, ) - names = _contact_names(await device.get_contacts()) + names = _contact_names(await ctx.devstate.contacts()) async def send(text: str) -> Optional[ChatMessage]: if conversation.is_channel: @@ -897,12 +897,12 @@ async def _make_paths_presenter( session = ctx.ui.session resolve = trace_runner.make_node_resolver( - await device.get_contacts(), ctx.repo.node_names() + await ctx.devstate.contacts(), ctx.repo.node_names() ) prefix_bytes = await _routing_prefix_bytes(ctx) self_name: Optional[str] = None try: - self_name = str((await device.get_self_info()).get("name") or "") or None + self_name = str((await ctx.devstate.self_info()).get("name") or "") or None except Exception: # noqa: BLE001 - a nameless self just skips the white highlight self_name = None diff --git a/meshterm/ui/courier_screen.py b/meshterm/ui/courier_screen.py index 2dc641e..ad49a98 100644 --- a/meshterm/ui/courier_screen.py +++ b/meshterm/ui/courier_screen.py @@ -106,8 +106,7 @@ async def open_courier(ctx: "AppContext") -> Optional[dict[str, Any]]: contacts: list[Contact] = [] try: if ctx.is_connected or ctx.settings.connect_on_start: - device = await ctx.device() - contacts = await device.get_contacts() + contacts = await ctx.devstate.contacts() except Exception: # noqa: BLE001 - the outbox renders fine without contacts contacts = [] diff --git a/meshterm/ui/dashboard_screen.py b/meshterm/ui/dashboard_screen.py index 6b35365..04a3286 100644 --- a/meshterm/ui/dashboard_screen.py +++ b/meshterm/ui/dashboard_screen.py @@ -662,7 +662,6 @@ async def open_dashboard(ctx: "AppContext") -> None: RuntimeError: If called outside the interactive menu (no full-screen session). """ from ..services import trace_runner - from .channels import read_channel_slots from .surface import TuiUi from .timemachine_screen import _routing_prefix_bytes @@ -675,10 +674,12 @@ async def open_dashboard(ctx: "AppContext") -> None: channels: list[tuple[str, bytes]] = [] try: if ctx.is_connected or ctx.settings.connect_on_start: - device = await ctx.device() - contacts = await device.get_contacts() - self_name = (await device.get_self_info()).get("name") or None - channels = [(s.name, s.secret) for s in await read_channel_slots(device)] + # Through the session cache: contacts and the channel-slot probe are the two + # slowest reads on a screen open, so reading them once (not per dashboard open) + # is what keeps navigation snappy over Bluetooth. + contacts = await ctx.devstate.contacts() + self_name = (await ctx.devstate.self_info()).get("name") or None + channels = [(s.name, s.secret) for s in await ctx.devstate.channel_slots()] except Exception: # noqa: BLE001 - the dashboard renders fine without contact names contacts = [] # Contacts first, every name the recorder ever overheard as the fallback — the diff --git a/meshterm/ui/timemachine_screen.py b/meshterm/ui/timemachine_screen.py index 4d49e23..0942388 100644 --- a/meshterm/ui/timemachine_screen.py +++ b/meshterm/ui/timemachine_screen.py @@ -875,8 +875,7 @@ async def _routing_prefix_bytes(ctx: "AppContext") -> int: try: if not (ctx.is_connected or ctx.settings.connect_on_start): return 0 - device = await ctx.device() - mode = await device.get_path_hash_mode() + mode = await ctx.devstate.path_hash_mode() except Exception: # noqa: BLE001 - optional read; absence just skips highlighting return 0 return (mode + 1) if isinstance(mode, int) and 0 <= mode <= 3 else 0 @@ -895,8 +894,7 @@ async def _contact_resolver(ctx: "AppContext") -> "NodeResolver": contacts = [] try: if ctx.is_connected or ctx.settings.connect_on_start: - device = await ctx.device() - contacts = await device.get_contacts() + contacts = await ctx.devstate.contacts() except Exception: # noqa: BLE001 - optional read; absence just leaves names stored-only contacts = [] return make_node_resolver(contacts) diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index bbf03ec..3503cd7 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -949,9 +949,12 @@ async def _open_session(ctx: "AppContext", target: Optional[str]) -> int: record_target = target if target is not None else PATH_TRACE_TARGET device = await ctx.device() - contacts = await device.get_contacts() + # Contacts and self-info come from the session cache (see DeviceState): the contacts + # table is a slow round-trip on a busy node, and this screen is reached often. The live + # ``device`` is still held for the traces this screen actually runs. + contacts = await ctx.devstate.contacts() resolve = trace_runner.make_node_resolver(contacts) - self_info = await device.get_self_info() + self_info = await ctx.devstate.self_info() device_label = str(self_info.get("name") or LOCAL_DEVICE_LABEL) device_hash = str(self_info.get("public_key") or "") or None @@ -961,7 +964,7 @@ async def _open_session(ctx: "AppContext", target: Optional[str]) -> int: # protocol default and what all stored evidence uses anyway. The user can override # it for the session through the screen's *Path width* action (see pick_width). try: - width_bytes = _collapse_trace_width(int(await device.get_path_hash_mode())) + width_bytes = _collapse_trace_width(int(await ctx.devstate.path_hash_mode())) except Exception: # noqa: BLE001 - optional read; the 1-byte default always works width_bytes = 1 device_width = width_bytes # remembered so the width dialog can mark the default diff --git a/meshterm/ui/tx_screen.py b/meshterm/ui/tx_screen.py index 1ba6374..b1f9e94 100644 --- a/meshterm/ui/tx_screen.py +++ b/meshterm/ui/tx_screen.py @@ -577,14 +577,16 @@ async def open_tx_optimize( raise RuntimeError("the live TX sweep is only available in the menu") session = ctx.ui.session device = await ctx.device() - contacts = await device.get_contacts() + # Contacts/self-info/routing width from the session cache (see DeviceState); the live + # ``device`` is still held for the sweep's own transmissions below. + contacts = await ctx.devstate.contacts() resolve = trace_runner.make_node_resolver(contacts) - self_info = await device.get_self_info() + self_info = await ctx.devstate.self_info() device_label = str(self_info.get("name") or "this node") device_hash = str(self_info.get("public_key") or "") or None try: - width_bytes = _collapse_trace_width(int(await device.get_path_hash_mode())) + width_bytes = _collapse_trace_width(int(await ctx.devstate.path_hash_mode())) except Exception: # noqa: BLE001 - optional read; the 1-byte default always works width_bytes = 1 diff --git a/meshterm/ui/watchtower_screen.py b/meshterm/ui/watchtower_screen.py index eafbdcb..362d2f3 100644 --- a/meshterm/ui/watchtower_screen.py +++ b/meshterm/ui/watchtower_screen.py @@ -77,8 +77,7 @@ async def open_watchtower(ctx: "AppContext") -> Optional[dict[str, Any]]: contacts: list[Contact] = [] try: if ctx.is_connected or ctx.settings.connect_on_start: - device = await ctx.device() - contacts = await device.get_contacts() + contacts = await ctx.devstate.contacts() except Exception: # noqa: BLE001 - the log and rules render fine without contacts contacts = [] diff --git a/tests/test_device_state.py b/tests/test_device_state.py new file mode 100644 index 0000000..9d09f0b --- /dev/null +++ b/tests/test_device_state.py @@ -0,0 +1,160 @@ +"""DeviceState session-cache tests: read once, serve cached, invalidate on write. + +The cache exists to keep screen navigation off the slow radio round-trips (contacts, +self-info, the channel probe). These tests pin the two behaviours that make it correct: +stable facts are fetched once and reused until an in-app write invalidates them, and the +contacts list refreshes in the background once it ages past the TTL without ever blocking a +read. A fake device counts round-trips so "served from cache" is assertable without hardware. +""" + +from __future__ import annotations + +import asyncio +import time +from types import SimpleNamespace + +from meshterm.services.device_state import DeviceState, _CONTACTS_TTL_S + + +class FakeDevice: + """A stand-in device that counts how often each cached read hits the wire.""" + + def __init__(self) -> None: + self.contacts_calls = 0 + self.self_info_calls = 0 + self.mode_calls = 0 + self.channel_calls = 0 + + async def get_contacts(self) -> list: + self.contacts_calls += 1 + return [f"contact-{self.contacts_calls}"] # a fresh identity per fetch, to spot refreshes + + async def get_self_info(self) -> dict: + self.self_info_calls += 1 + return {"name": "node", "tx_power": 20} + + async def get_path_hash_mode(self) -> int: + self.mode_calls += 1 + return 2 + + async def get_channel(self, idx: int): + # One configured slot at index 0, then the firmware "rejects" index 1 to end the probe. + self.channel_calls += 1 + if idx == 0: + return {"channel_name": "public", "channel_secret": b"\x00" * 16} + raise RuntimeError("out of range") + + +def _devstate(device: FakeDevice) -> DeviceState: + """A DeviceState over a fake ctx exposing just device() and a silent logger.""" + + async def device_getter(): + return device + + ctx = SimpleNamespace( + device=device_getter, + log=SimpleNamespace(debug=lambda *a, **k: None), + ) + return DeviceState(ctx) # type: ignore[arg-type] + + +def test_stable_facts_are_fetched_once_and_served_from_cache() -> None: + """self-info, path-hash mode, and channels read the radio once, then reuse the value.""" + dev = FakeDevice() + ds = _devstate(dev) + + async def run() -> None: + for _ in range(3): + assert (await ds.self_info())["name"] == "node" + assert await ds.path_hash_mode() == 2 + assert [s.name for s in await ds.channel_slots()] == ["public"] + + asyncio.run(run()) + assert dev.self_info_calls == 1 + assert dev.mode_calls == 1 + # The channel probe ran once (idx 0 ok, idx 1 rejected) and was cached wholesale. + assert dev.channel_calls == 2 + + +def test_contacts_served_from_cache_within_ttl() -> None: + """Repeated contacts reads inside the TTL hit the wire exactly once.""" + dev = FakeDevice() + ds = _devstate(dev) + + async def run() -> None: + first = await ds.contacts() + for _ in range(5): + assert await ds.contacts() is first # same cached list object + + asyncio.run(run()) + assert dev.contacts_calls == 1 + + +def test_contacts_refresh_in_background_past_ttl() -> None: + """Past the TTL a read returns the stale list instantly and refreshes behind it.""" + dev = FakeDevice() + ds = _devstate(dev) + + async def run() -> None: + stale = await ds.contacts() # first fetch + assert dev.contacts_calls == 1 + # Age the cache past the TTL, then read: the read must return immediately (the stale + # copy) and schedule a background refresh rather than block on the slow call. + ds._contacts_at = time.monotonic() - _CONTACTS_TTL_S - 1 + served = await ds.contacts() + assert served is stale # served the old list, did not block on a re-fetch + # Let the scheduled background refresh run. + await asyncio.gather(*list(ds._tasks)) + assert dev.contacts_calls == 2 # refreshed behind the read + assert (await ds.contacts())[0] == "contact-2" # now serving the fresh list + + asyncio.run(run()) + + +def test_force_bypasses_the_contacts_cache() -> None: + """A forced read always re-fetches, for the rare caller that needs it fresh.""" + dev = FakeDevice() + ds = _devstate(dev) + + async def run() -> None: + await ds.contacts() + await ds.contacts(force=True) + + asyncio.run(run()) + assert dev.contacts_calls == 2 + + +def test_invalidation_forces_a_re_read() -> None: + """Each invalidate drops exactly its own entry so the next read re-fetches it.""" + dev = FakeDevice() + ds = _devstate(dev) + + async def run() -> None: + await ds.self_info(); await ds.path_hash_mode(); await ds.channel_slots(); await ds.contacts() + # invalidate_config drops self-info + path-hash mode together (the config editor's write). + ds.invalidate_config() + await ds.self_info(); await ds.path_hash_mode() + assert dev.self_info_calls == 2 and dev.mode_calls == 2 + # channels and contacts were untouched by that invalidation. + assert dev.channel_calls == 2 and dev.contacts_calls == 1 + ds.invalidate_channels() + await ds.channel_slots() + assert dev.channel_calls == 4 # probed again + + asyncio.run(run()) + + +def test_reset_clears_everything() -> None: + """A reconnect's reset drops the whole cache so every fact is re-read on next use.""" + dev = FakeDevice() + ds = _devstate(dev) + + async def run() -> None: + await ds.self_info(); await ds.contacts(); await ds.path_hash_mode() + ds.reset() + await ds.self_info(); await ds.contacts(); await ds.path_hash_mode() + + asyncio.run(run()) + assert dev.self_info_calls == 2 + assert dev.contacts_calls == 2 + assert dev.mode_calls == 2