mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 06:15:09 +00:00
* feat(starlark,on-demand): the third-party fixes worth taking, plus an MQTT bridge Analysis of ant456/ledmatrix-fixes-repo, a third-party collection of patches and services built while running this project on Starlark apps under MQTT control. Its patches are whole-file copies taken against an older tree, so applying them as written would revert #523's frame pacing, #534's display() bool returns and the GitHub token masking in plugins_manager.js. Three of its claimed fixes are already in main, and its api_v3 Starlark routes are #535's. What follows is the rest -- verified against current code, and reimplemented where the patch's approach did not hold up. **On-demand display.** `pinned` reached the controller from the API, was stored on it and republished in the status payload, but never narrowed the rotation -- a pinned request still cycled every mode its plugin owns. Right for a sports plugin, whose modes are views of one subject; wrong for a plugin whose modes are unrelated, which is every Starlark app. Now honoured, and it survives a restart. Restarting while on-demand was active loaded *only* the on-demand plugin, so normal rotation had nothing to return to for the life of the process -- and a restart mid-session is routine, since that is how an update is applied. The panel came back cycling one plugin's modes with no way out but clearing the cache by hand. Every enabled plugin loads now; on-demand still resumes on its saved mode. Stop requests are exempt from the duplicate guards on purpose, so that a second click stops a mode a race left running -- which means consuming the mailbox is the only thing that ends one. It was never consumed, so the same stop was re-read and re-processed on every poll, forever. Both paths now share one compare-before-delete helper. **Starlark rendering.** `extract_schema` parsed the source with a regex, which can only see option lists written out literally: an app whose dropdown is filled from a live API call inside `get_schema()` came back empty, and the config form offered nothing to pick. Now runs `pixlet schema`, which executes the app, and falls back to the parser when Pixlet is absent, too old for the subcommand, or the app fails to run. The third-party patch replaced the parser outright and hardcoded /usr/local/bin/pixlet; this keeps the fallback and the binary search. A `|` in a config value was dropped by a shell-metacharacter filter, though the command is a list with no shell involved -- and apps do use it as a separator inside one value. The key went missing silently and the app rendered its own "not configured" screen with nothing to say why. And a 0-byte render was reported as success: Pixlet exits 0 and writes nothing when an app has no content, which read downstream as a working app drawing a black panel. **Starlark display.** `display()` ignored the mode it was called with, so a specific app could not be addressed. It now accepts `display_mode` -- which is the whole mechanism, since the controller inspects the signature before passing it. Found while there: `_select_next_app` ran only while `current_app` was unset, so with several apps installed the first was picked once and shown forever while the rest were rendered on schedule and never displayed. And `enable_scrolling` was missing, so multi-frame apps were called once per rotation slot and never advanced past frame one. **GET /api/v3/display/modes.** Every mode that can be requested on-demand, with the plugin that owns it. Nothing exposed this, so anything driving the display from outside the web UI read each plugin's manifest.json off disk and reimplemented PluginManager's fallbacks. It also triggers discovery, which is otherwise lazy and normally happens because a person opened the dashboard. **integrations/mqtt_bridge.** Home Assistant control over MQTT Discovery: a mode select, a stop button, power, brightness. Rewritten against the API rather than the filesystem, so it needs no read access to config.json and cannot drift from the web UI. paho-mqtt 2.x VERSION2, TLS, an availability topic that is also the last will, and secrets from the environment. **Two opt-in extras.** A DNS single-request unit, for glibc's parallel A/AAAA lookup stalling ~5s per name on routers that answer only the A query -- which makes any plugin calling an external API slow and Starlark apps, which have a render timeout, fail outright. And a Pixlet config editor: a script you run and Ctrl+C rather than the third-party version's always-on unauthenticated Flask service, since it stops the display for the length of a session. Neither is installed by default. Long Starlark app names now wrap instead of overflowing their card. 115 new tests across 5 files. Also unblocked test_starlark_display_contract.py, which was silently skipping wherever fcntl is absent. Whole suite: no new failures against main. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(mqtt_bridge): the five issues Codacy flagged on this branch All in the new bridge, all real: * requests floor was 2.31.0, which carries CVE-2024-35195, CVE-2024-47081 and CVE-2026-25645. Raised to >=2.33.0,<3.0.0, which is what the project's own requirements.txt already pins. * `import time` was never used. * `"mqtt_password": None` in DEFAULTS read as a hardcoded credential. It is the "no password configured" default; marked nosec B105, the convention used elsewhere in the repo. Also dropped an unused `build_app` from the display-modes test imports. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: the review findings on this PR Nine of CodeRabbit's ten, plus the CodeQL alert. The tenth is wrong and is answered below. **One bad config section blanked the whole mode list.** `/display/modes` read `full_config.get(plugin_id, {}).get('enabled')`, so a non-dict under a plugin id -- a shape DisplayController already guards, so it happens -- raised AttributeError mid-loop and answered 500 with no modes at all. Every MQTT bridge entity is built from that list. Now skipped with a warning. **The DNS scripts reported success they had not earned.** Three separate paths: `resolvconf -u` failing was swallowed by `|| true`; the systemd-resolved branch exited 0 without applying anything, so the oneshot unit recorded success while the workaround was inactive; and the installer's `|| echo` turned a failed start into "installation complete." with exit 0. All three now fail loudly. `single-request` is a glibc resolv.conf option with no resolved.conf equivalent, so on those hosts the honest answer is that it cannot be applied. A NetworkManager-generated resolv.conf is regenerated on connection changes, not only at boot, and the unit is oneshot with RemainAfterExit -- so the option can vanish mid-boot with nothing to put it back. Now detected and stated plainly rather than implied to be permanent. **`Before=` does not order a manual restart.** It only orders units already in the same transaction, so `systemctl restart ledmatrix` could bypass the fix. install_dns_fix.sh now writes a ledmatrix.service drop-in with Wants= and After=. Wants=, not Requires=: a DNS workaround failing should not stop the display. **The Pixlet editor's `--lan` is gone.** `pixlet serve` has no authentication, and a printed warning is not access control. Loopback only, with the SSH port-forward in the header where the flag used to be documented -- SSH does the authenticating and nothing is left listening. **The MQTT example config now defaults to TLS** on 8883. The installer copies it verbatim, and without TLS the broker password and every command cross the network in cleartext. A plaintext broker is still supported and documented, and the bridge warns once at startup when a password is configured without TLS. **Not taken: "the upstream Pixlet CLI has no `schema` subcommand."** Upstream tidbyt/pixlet has none, but `scripts/download_pixlet.sh` installs `tronbyt/pixlet`, whose `cmd/schema.go` is `schema [PATH]` -> JSON on stdout, built on `runtime.NewAppletFromPath`, so it does execute `get_schema()`. That is exactly what extract_schema_via_pixlet calls. A binary without the subcommand exits non-zero and falls back to the source parser, which is already covered by a test. **CodeQL stack-trace exposure: not taken either.** I removed `details` first and that broke test_web_error_detail.py::test_no_api_v3_handler_discards_its_exception, which enforces `describe_exception` across all ~75 handlers -- written because a device with failing storage answered "see logs for details" from the log viewer itself. describe_exception redacts credentials; the trade-off is the project's and is already made. Restored, with the reasoning in a comment. 11 new tests. Whole suite: no new failures against main, 4127 passed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
209 lines
8.8 KiB
Python
209 lines
8.8 KiB
Python
"""On-demand behaviour that a person can ask for but the controller ignored.
|
|
|
|
Three separate gaps, all reachable from the web UI's force-display dialog:
|
|
|
|
* `pinned` was accepted by the API, stored on the controller and published
|
|
back in the status payload, but never narrowed the rotation -- a pinned
|
|
request still cycled every mode its plugin owns;
|
|
* restarting while on-demand was active loaded *only* the on-demand plugin,
|
|
so normal rotation had nothing to return to for the life of the process;
|
|
* a stop request was exempt from the duplicate guards on purpose and was
|
|
never removed from the mailbox, so it was re-processed on every poll
|
|
forever.
|
|
"""
|
|
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
|
|
|
|
def _plugin_with_modes(controller, plugin_id, modes):
|
|
"""Register `modes` as loaded modes belonging to `plugin_id`."""
|
|
controller.plugin_display_modes[plugin_id] = list(modes)
|
|
for mode in modes:
|
|
controller.plugin_modes[mode] = MagicMock(spec=[])
|
|
controller.mode_to_plugin_id[mode] = plugin_id
|
|
|
|
|
|
class TestPinnedNarrowsTheRotation:
|
|
"""A pinned request shows the one mode that was asked for.
|
|
|
|
Unpinned stays the default: a sports plugin's modes are views of one
|
|
subject, so rotating them is right. A Starlark plugin's modes are
|
|
unrelated widgets, so it is not.
|
|
"""
|
|
|
|
MODES = ['app_a', 'app_b', 'app_c']
|
|
|
|
def _activate(self, controller, pinned):
|
|
_plugin_with_modes(controller, 'starlark-apps', self.MODES)
|
|
controller.available_modes = list(self.MODES)
|
|
controller._activate_on_demand({
|
|
'request_id': 'r1',
|
|
'action': 'start',
|
|
'plugin_id': 'starlark-apps',
|
|
'mode': 'app_b',
|
|
'pinned': pinned,
|
|
})
|
|
|
|
def test_pinned_rotation_holds_the_requested_mode(self, test_display_controller):
|
|
c = test_display_controller
|
|
self._activate(c, pinned=True)
|
|
assert c.on_demand_modes == ['app_b']
|
|
|
|
def test_unpinned_still_rotates_the_whole_plugin(self, test_display_controller):
|
|
c = test_display_controller
|
|
self._activate(c, pinned=False)
|
|
assert set(c.on_demand_modes) == set(self.MODES)
|
|
|
|
def test_pinned_still_starts_on_the_requested_mode(self, test_display_controller):
|
|
c = test_display_controller
|
|
self._activate(c, pinned=True)
|
|
assert c.current_display_mode == 'app_b'
|
|
|
|
def test_the_pin_is_recorded_for_the_status_payload(self, test_display_controller):
|
|
c = test_display_controller
|
|
self._activate(c, pinned=True)
|
|
assert c.on_demand_pinned is True
|
|
|
|
def test_an_unresolvable_pin_does_not_empty_the_rotation(self, test_display_controller):
|
|
"""A pin naming a mode outside the plugin must not leave nothing to show."""
|
|
c = test_display_controller
|
|
_plugin_with_modes(c, 'starlark-apps', self.MODES)
|
|
assert c._apply_on_demand_pin(list(self.MODES), 'not_a_mode', True) == self.MODES
|
|
|
|
|
|
class TestPinSurvivesARestart:
|
|
"""The pin is part of the request being resumed, not a per-session flag."""
|
|
|
|
def test_restored_pinned_state_narrows_the_rotation(self, test_display_controller):
|
|
c = test_display_controller
|
|
_plugin_with_modes(c, 'starlark-apps', ['app_a', 'app_b', 'app_c'])
|
|
c.on_demand_active = True
|
|
c.on_demand_plugin_id = 'starlark-apps'
|
|
c.on_demand_mode = 'app_c'
|
|
c.on_demand_pinned = True
|
|
|
|
c._populate_on_demand_modes_from_plugin()
|
|
assert c.on_demand_modes == ['app_c']
|
|
|
|
def test_restored_unpinned_state_keeps_every_mode(self, test_display_controller):
|
|
c = test_display_controller
|
|
_plugin_with_modes(c, 'starlark-apps', ['app_a', 'app_b', 'app_c'])
|
|
c.on_demand_active = True
|
|
c.on_demand_plugin_id = 'starlark-apps'
|
|
c.on_demand_mode = 'app_c'
|
|
c.on_demand_pinned = False
|
|
|
|
c._populate_on_demand_modes_from_plugin()
|
|
assert set(c.on_demand_modes) == {'app_a', 'app_b', 'app_c'}
|
|
|
|
|
|
class TestRestartDoesNotStarveTheOtherPlugins:
|
|
"""Restarting mid-on-demand used to load only the on-demand plugin.
|
|
|
|
Restarts during an on-demand session are routine -- it is how an update or
|
|
a config change is applied -- and the panel came back cycling one plugin's
|
|
modes and nothing else until the on-demand cache was cleared by hand.
|
|
"""
|
|
|
|
DISCOVERED = ['clock', 'weather', 'starlark-apps', 'disabled-one']
|
|
|
|
@pytest.fixture
|
|
def controller(self, test_display_controller):
|
|
c = test_display_controller
|
|
c.config.update({
|
|
'clock': {'enabled': True},
|
|
'weather': {'enabled': True},
|
|
'starlark-apps': {'enabled': True},
|
|
'disabled-one': {'enabled': False},
|
|
})
|
|
return c
|
|
|
|
def test_every_enabled_plugin_still_loads(self, controller):
|
|
selected = controller._select_startup_plugins(
|
|
self.DISCOVERED, {'plugin_id': 'starlark-apps', 'mode': 'app_a'})
|
|
assert set(selected) == {'clock', 'weather', 'starlark-apps'}
|
|
|
|
def test_disabled_plugins_are_still_left_out(self, controller):
|
|
selected = controller._select_startup_plugins(
|
|
self.DISCOVERED, {'plugin_id': 'starlark-apps', 'mode': 'app_a'})
|
|
assert 'disabled-one' not in selected
|
|
|
|
def test_the_on_demand_state_is_still_restored(self, controller):
|
|
controller._select_startup_plugins(
|
|
self.DISCOVERED,
|
|
{'plugin_id': 'starlark-apps', 'mode': 'app_a', 'pinned': True})
|
|
assert controller.on_demand_active is True
|
|
assert controller.on_demand_plugin_id == 'starlark-apps'
|
|
assert controller.on_demand_mode == 'app_a'
|
|
assert controller.on_demand_pinned is True
|
|
|
|
def test_a_disabled_on_demand_plugin_is_enabled_and_loaded(self, controller):
|
|
"""Otherwise the mode being resumed has nothing behind it."""
|
|
selected = controller._select_startup_plugins(
|
|
self.DISCOVERED, {'plugin_id': 'disabled-one', 'mode': 'x'})
|
|
assert 'disabled-one' in selected
|
|
assert controller.config['disabled-one']['enabled'] is True
|
|
|
|
def test_an_unknown_on_demand_plugin_falls_back_to_normal(self, controller):
|
|
selected = controller._select_startup_plugins(
|
|
self.DISCOVERED, {'plugin_id': 'uninstalled', 'mode': 'x'})
|
|
assert set(selected) == {'clock', 'weather', 'starlark-apps'}
|
|
assert controller.on_demand_active is False
|
|
|
|
def test_no_on_demand_config_is_a_normal_startup(self, controller):
|
|
selected = controller._select_startup_plugins(self.DISCOVERED, None)
|
|
assert set(selected) == {'clock', 'weather', 'starlark-apps'}
|
|
assert controller.on_demand_active is False
|
|
|
|
|
|
class TestStopRequestsAreConsumed:
|
|
"""A stop request is exempt from the duplicate guards, so the mailbox
|
|
delete is the only thing that ends it."""
|
|
|
|
STOP = {'request_id': 'S1', 'action': 'stop'}
|
|
|
|
def _arrange(self, controller, active):
|
|
controller.on_demand_active = active
|
|
controller.on_demand_status = 'active' if active else 'idle'
|
|
controller._last_on_demand_poll = None
|
|
controller.cache_manager.get = MagicMock(
|
|
side_effect=lambda key, *a, **kw:
|
|
self.STOP if key == 'display_on_demand_request' else None)
|
|
controller.cache_manager.set = MagicMock()
|
|
controller.cache_manager.delete = MagicMock()
|
|
controller._clear_on_demand = MagicMock()
|
|
|
|
def test_a_handled_stop_is_removed_from_the_mailbox(self, test_display_controller):
|
|
c = test_display_controller
|
|
self._arrange(c, active=True)
|
|
c._poll_on_demand_requests()
|
|
c.cache_manager.delete.assert_called_once_with('display_on_demand_request')
|
|
|
|
def test_a_stop_arriving_while_idle_is_also_removed(self, test_display_controller):
|
|
"""Otherwise a stop sent to an idle display re-fires forever."""
|
|
c = test_display_controller
|
|
self._arrange(c, active=False)
|
|
c._poll_on_demand_requests()
|
|
c.cache_manager.delete.assert_called_once_with('display_on_demand_request')
|
|
|
|
def test_the_stop_is_still_acted_on(self, test_display_controller):
|
|
c = test_display_controller
|
|
self._arrange(c, active=True)
|
|
c._poll_on_demand_requests()
|
|
c._clear_on_demand.assert_called_once_with(reason='requested-stop')
|
|
|
|
def test_a_start_racing_in_behind_a_stop_is_not_discarded(self, test_display_controller):
|
|
"""The compare-before-delete applies to stops too."""
|
|
c = test_display_controller
|
|
self._arrange(c, active=True)
|
|
newer = {'request_id': 'S2', 'action': 'start', 'plugin_id': 'p', 'mode': 'm'}
|
|
reads = iter([self.STOP, newer])
|
|
c.cache_manager.get = MagicMock(
|
|
side_effect=lambda key, *a, **kw:
|
|
next(reads, newer) if key == 'display_on_demand_request' else None)
|
|
|
|
c._poll_on_demand_requests()
|
|
assert c.cache_manager.delete.call_count == 0
|