Files
LEDMatrix/src/config_service.py
T
ChuckandClaude Opus 5.5 84afa9d64f refactor: delete dead Python code in the core (and stop storing Wi-Fi passwords) (#608)
* refactor(plugins): remove the no-op PluginHealthMonitor

Its monitor loop did nothing (`if callbacks: pass`), register_health_check
had no callers and api_v3.health_monitor was never read by any route. The
live health data comes from PluginHealthTracker, which is untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(store): drop the never-set uninstall tombstones

Nothing in production called mark_recently_uninstalled, so the
reconciler's was_recently_uninstalled check was always False. The
persistent uninstall registry is what actually stops resurrection; the
reconciler test now exercises that gate instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(common): delete unused config/display/game helpers, utils and error_handler

Nothing in core, the web UI, scripts or the plugin monorepo imports
config_helper, display_helper, game_helper, utils or error_handler; only
their own tests did. The error_handler re-exports leave src.common's
__all__; APIHelper, TextHelper, ScrollHelper, LogoHelper and the adaptive
layout exports are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(config): drop ConfigService's unused versioning and save API

ConfigVersion, get_version/get_version_history/get_version_config,
rollback, save_config, reload, get_plugin_config and the backward-compat
load_config/get_config_path/get_secrets_path had no callers. The display
controller only uses get_config, subscribe, unsubscribe and shutdown,
plus the file watcher. Change detection now compares against the
current checksum instead of the last history entry.

The subscriber tests asserted `callback.called or True`; they now
reload the way the watcher does and assert the notification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(plugins): drop unread plugin state history and callbacks

plugin_state.PluginStateManager kept a bounded per-plugin transition
history that only get_state_history (tests only) read; get_state_info
reports a separate lifetime count, which stays. set_error_info and
record_display had no callers, and set_state_with_error's `error`
argument only fed the history.

The web-side state_manager.PluginStateManager loses
subscribe_to_state_changes, _notify_callbacks, set_plugin_error and
get_state_version, none of which had callers; with no subscribers the
old-state copy in update_plugin_state went with them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(plugins): remove unused PluginManager methods and attribute guards

update_all_plugins was only called by a test (the display loop uses
run_scheduled_updates); get_plugin_health_metrics,
get_plugin_resource_metrics and get_plugin_state had no callers; and
plugin_modules was written but never read. plugin_directories is now
initialised in __init__, so the hasattr() guards around it go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(plugins): remove unused executor, loader, store and package helpers

- PluginExecutor.execute_safe: no callers.
- PluginLoader._parse_semver: only its own tests; compatibility.parse_semver
  is the live copy and test_compatibility.py already covers it.
- PluginStoreManager.get_installed_plugin_info: no callers.
- PluginResourceMonitor._local: never read.
- src.plugin_system.get_store_manager and __api_version__: no importers in
  core, scripts or the plugin monorepo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(wifi): stop storing Wi-Fi passwords in wifi_config.json

WiFiManager appended every joined network's SSID and password, in
plaintext, to saved_networks in config/wifi_config.json, and nothing
(web UI, backup restore, scripts) ever read them back: NetworkManager
keeps its own credentials. The writes are gone, and loading the config
now drops any saved_networks key and rewrites the file, so passwords
already on disk are scrubbed.

Also removes _check_dnsmasq_conflict (never called) and _detect_trixie,
whose result only reached one log line, along with the
NM_CONNECTIONS_PATHS constant only it used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(display): remove unreachable and unused DisplayController code

- _follower_rebuild_scroll_image: never called.
- mode_duration (never read) and last_mode_change (write-only).
- The `chosen_cap <= 0` branch: chosen_cap is either the minimum of
  caps already filtered to > 0 or DEFAULT_DYNAMIC_DURATION_CAP (180).
- The `max_duration < min_duration` branch directly after
  `max_duration = max(min_duration, max_duration)`.
- The circuit-breaker branch's `display_result = False` and
  `manager_to_display = None`: the first is overwritten a few lines
  later, the second is already None there.
- The bool-to-bool conversion of execute_display's result, which is
  always a bool.
- The `loaded_plugins` lookup in _update_modules: PluginManager has no
  such attribute, so it always fell through to `plugins`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(vegas): remove unused config update, boundary finder and refresh

VegasModeConfig.update had no callers outside its own tests (the
coordinator rebuilds the config with from_config on a change);
geometry.find_item_boundary and StreamManager._refresh_plugin_content
had no callers at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(run): drop the debug block that pretended to import the plugin system

In debug mode run.py put src/plugin_system itself on sys.path and printed
"Plugin system import successful" without importing anything. Nothing
imports plugin_system modules by bare name, so the path entry did
nothing either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: delete tests that test nothing

- test/plugins/test_{basketball_scoreboard,calendar,clock_simple,
  odds_ticker,soccer_scoreboard,text_display}.py skip everywhere the named
  plugins are not installed, including CI (LEDMATRIX_PLUGINS_DIR holds only
  the fixture plugin); test_plugin_matrix.py already covers every
  discovered plugin. Their PluginTestBase and the fixtures only it used
  (plugins_dir, mock_display_manager, mock_cache_manager,
  mock_plugin_manager, base_plugin_config in test/plugins/conftest.py) go
  with them.
- test_plugin_system.py: test_discover_plugins (body was `pass`) and
  test_dependency_check (a comment), plus the test_plugin_manager fixture
  only the former requested.
- test_display_manager.py: test_draw_image asserted that an image it had
  just assigned was not None.
- test_display_controller.py: the rotation and schedule-override tests
  re-implemented the run-loop arithmetic inline and asserted on their own
  result without calling the controller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: expect one plugin_last_update success stamp after update_all_plugins

EveryStampRecordsACompletion required at least two success-path stamps;
the second was update_all_plugins, removed as test-only. The worker and
synchronous paths share the remaining stamp in _execute_update_now, and
the check that every stamp calls _note_update_completed is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:36:26 -04:00

295 lines
10 KiB
Python

"""
Configuration Service
Provides centralized configuration management with hot-reload support
and change notifications.
This service wraps ConfigManager and adds:
- File watching for automatic reload
- Change notifications to subscribers
- Thread-safe configuration access
"""
import json
import time
import threading
from pathlib import Path
from typing import Dict, Any, Optional, List, Callable
from collections import defaultdict
import logging
import hashlib
from src.exceptions import ConfigError
from src.logging_config import get_logger
from src.config_manager import ConfigManager
class ConfigService:
"""
Centralized configuration service with hot-reload.
Features:
- Automatic file watching and reload
- Change notifications to subscribers
- Thread-safe access
"""
def __init__(
self,
config_manager: Optional[ConfigManager] = None,
enable_hot_reload: bool = True
) -> None:
"""
Initialize the configuration service.
Args:
config_manager: Optional ConfigManager instance (creates new if None)
enable_hot_reload: Whether to enable automatic file watching
"""
self.logger: logging.Logger = get_logger(__name__)
self.config_manager: ConfigManager = config_manager or ConfigManager()
self.enable_hot_reload: bool = enable_hot_reload
# Thread safety
self._lock: threading.RLock = threading.RLock()
# Current configuration
self._current_config: Dict[str, Any] = {}
self._current_checksum: Optional[str] = None
self._last_modified: Dict[str, float] = {}
# Subscribers for change notifications
# Format: {plugin_id or component_name: [callbacks]}
self._subscribers: Dict[str, List[Callable[[Dict[str, Any], Dict[str, Any]], None]]] = defaultdict(list)
# File watching
self._watch_thread: Optional[threading.Thread] = None
self._watch_interval: float = 2.0 # Check every 2 seconds
self._stop_watching: bool = False
# Load initial configuration
self._load_config()
# Start file watching if enabled
if self.enable_hot_reload:
self._start_file_watching()
def _calculate_checksum(self, config: Dict[str, Any]) -> str:
"""Calculate checksum of configuration for change detection."""
config_str = json.dumps(config, sort_keys=True)
return hashlib.sha256(config_str.encode()).hexdigest()
def _load_config(self) -> bool:
"""
Load configuration from ConfigManager.
Returns:
True if config changed, False otherwise
"""
try:
new_config = self.config_manager.load_config()
new_checksum = self._calculate_checksum(new_config)
with self._lock:
# Check if config actually changed
if new_checksum == self._current_checksum:
self.logger.debug("Configuration unchanged, skipping reload")
return False
# Store old config for change detection
old_config = self._current_config.copy()
# Update current config
self._current_config = new_config
self._current_checksum = new_checksum
# Notify subscribers
self._notify_subscribers(old_config, new_config)
self.logger.info(
"Configuration reloaded (checksum: %s)",
new_checksum[:8]
)
return True
except ConfigError as e:
self.logger.error("Error loading configuration: %s", e, exc_info=True)
return False
except Exception as e:
self.logger.error("Unexpected error loading configuration: %s", e, exc_info=True)
return False
def _notify_subscribers(self, old_config: Dict[str, Any], new_config: Dict[str, Any]) -> None:
"""
Notify all subscribers of configuration changes.
Args:
old_config: Previous configuration
new_config: New configuration
"""
# Notify global subscribers (key: '*')
for callback in self._subscribers.get('*', []):
try:
callback(old_config, new_config)
except Exception as e:
self.logger.error("Error in global config change callback: %s", e, exc_info=True)
# Notify plugin-specific subscribers
for plugin_id in self._subscribers.keys():
if plugin_id == '*':
continue
old_plugin_config = old_config.get(plugin_id, {})
new_plugin_config = new_config.get(plugin_id, {})
# Only notify if plugin config actually changed
if old_plugin_config != new_plugin_config:
for callback in self._subscribers[plugin_id]:
try:
callback(old_plugin_config, new_plugin_config)
except Exception as e:
self.logger.error(
"Error in config change callback for %s: %s",
plugin_id,
e,
exc_info=True
)
def _check_file_changes(self) -> bool:
"""
Check if configuration files have been modified.
Returns:
True if files changed, False otherwise
"""
config_path = Path(self.config_manager.get_config_path())
secrets_path = Path(self.config_manager.get_secrets_path())
changed = False
# Check main config file
if config_path.exists():
mtime = config_path.stat().st_mtime
if mtime != self._last_modified.get(str(config_path), 0):
self._last_modified[str(config_path)] = mtime
changed = True
# Check secrets file
if secrets_path.exists():
mtime = secrets_path.stat().st_mtime
if mtime != self._last_modified.get(str(secrets_path), 0):
self._last_modified[str(secrets_path)] = mtime
changed = True
return changed
def _file_watcher_loop(self) -> None:
"""Main loop for file watching."""
self.logger.info("Configuration file watcher started")
# Initialize last modified times
config_path = Path(self.config_manager.get_config_path())
secrets_path = Path(self.config_manager.get_secrets_path())
if config_path.exists():
self._last_modified[str(config_path)] = config_path.stat().st_mtime
if secrets_path.exists():
self._last_modified[str(secrets_path)] = secrets_path.stat().st_mtime
while not self._stop_watching:
try:
if self._check_file_changes():
self.logger.info("Configuration files changed, reloading...")
self._load_config()
# Sleep with periodic checks for stop signal
for _ in range(int(self._watch_interval)):
if self._stop_watching:
break
time.sleep(1)
except Exception as e:
self.logger.error("Error in file watcher loop: %s", e, exc_info=True)
time.sleep(self._watch_interval)
self.logger.info("Configuration file watcher stopped")
def _start_file_watching(self) -> None:
"""Start the file watching thread."""
if self._watch_thread and self._watch_thread.is_alive():
return
self._stop_watching = False
self._watch_thread = threading.Thread(
target=self._file_watcher_loop,
name="ConfigService-Watcher",
daemon=True
)
self._watch_thread.start()
self.logger.debug("File watching thread started")
def _stop_file_watching(self) -> None:
"""Stop the file watching thread."""
if self._watch_thread and self._watch_thread.is_alive():
self._stop_watching = True
self._watch_thread.join(timeout=5.0)
if self._watch_thread.is_alive():
self.logger.warning("File watching thread did not stop gracefully")
def get_config(self) -> Dict[str, Any]:
"""
Get current configuration (thread-safe).
Returns:
Current configuration dictionary
"""
with self._lock:
return self._current_config.copy()
def subscribe(
self,
callback: Callable[[Dict[str, Any], Dict[str, Any]], None],
plugin_id: Optional[str] = None
) -> None:
"""
Subscribe to configuration changes.
Args:
callback: Function to call when config changes
Signature: callback(old_config, new_config)
plugin_id: Optional plugin ID to subscribe to specific plugin changes
If None, subscribes to all changes
"""
key = plugin_id or '*'
with self._lock:
if callback not in self._subscribers[key]:
self._subscribers[key].append(callback)
self.logger.debug("Subscribed to config changes for %s", key)
def unsubscribe(
self,
callback: Callable[[Dict[str, Any], Dict[str, Any]], None],
plugin_id: Optional[str] = None
) -> None:
"""
Unsubscribe from configuration changes.
Args:
callback: Callback function to remove
plugin_id: Optional plugin ID (must match subscription)
"""
key = plugin_id or '*'
with self._lock:
if callback in self._subscribers[key]:
self._subscribers[key].remove(callback)
self.logger.debug("Unsubscribed from config changes for %s", key)
def shutdown(self) -> None:
"""Shutdown the configuration service."""
self.logger.info("Shutting down configuration service")
self._stop_file_watching()
with self._lock:
self._subscribers.clear()