From 56badac9904d370dca605ab9e5df6afc7356b007 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 26 Jul 2026 05:55:28 +0200 Subject: [PATCH] =?UTF-8?q?feat(p1-2):=20Plugin-State-Datei=20=E2=80=94=20?= =?UTF-8?q?atomare=20Hilfsfunktionen=20(=5Fget=5Fplugin=5Fstate=5Fpath,=20?= =?UTF-8?q?=5Fread=5Fplugin=5Fstate,=20=5Fwrite=5Fplugin=5Fstate)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/archivar/presence_engine.py | 69 +++++++++++++++++++ plugin/archivar/tests/test_presence_engine.py | 56 +++++++++++++++ 2 files changed, 125 insertions(+) diff --git a/plugin/archivar/presence_engine.py b/plugin/archivar/presence_engine.py index c1bbd5f..74cde6f 100644 --- a/plugin/archivar/presence_engine.py +++ b/plugin/archivar/presence_engine.py @@ -14,10 +14,12 @@ import json import logging import os import subprocess +import tempfile import threading import time import urllib.request import urllib.error +from datetime import datetime, timezone from typing import Optional, Dict, Callable logger = logging.getLogger(__name__) @@ -30,6 +32,73 @@ if not logger.handlers: logger.propagate = False # Don't double-log to root +# ═══════════════════════════════════════════════════════════════════════════ +# P1-2: Plugin-State-Datei — atomare Hilfsfunktionen +# ═══════════════════════════════════════════════════════════════════════════ + +PLUGIN_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state") +PLUGIN_STATE_FILENAME = "hermes_rocket_plugin.json" +PLUGIN_STATE_SCHEMA_VERSION = 1 + + +def _get_plugin_state_path() -> str: + """Return the path to the plugin state file. + + Returns: + Absolute path to ~/.hermes/plugin_state/hermes_rocket_plugin.json + """ + return os.path.join(PLUGIN_STATE_DIR, PLUGIN_STATE_FILENAME) + + +def _read_plugin_state(path: str) -> dict: + """Read the plugin state file, returning {} if missing or corrupt. + + Args: + path: Absolute path to the plugin state JSON file. + + Returns: + Parsed dict, or empty dict on any error. + """ + try: + if not os.path.exists(path): + return {} + with open(path, 'r') as f: + return json.load(f) + except (json.JSONDecodeError, IOError, OSError) as e: + logger.debug("[plugin_state] read failed: %s", e) + return {} + + +def _write_plugin_state(path: str, data: dict) -> None: + """Atomically write the plugin state file (write-temp + rename). + + Args: + path: Absolute path to the plugin state JSON file. + data: Dict to serialize as JSON. + """ + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + # Write to temp file in same directory (same filesystem → atomic rename) + fd, tmp_path = tempfile.mkstemp( + suffix=".tmp", + prefix="plugin_state_", + dir=os.path.dirname(path), + ) + try: + with os.fdopen(fd, 'w') as f: + json.dump(data, f, ensure_ascii=False) + os.replace(tmp_path, path) # atomic on POSIX + except Exception: + # Clean up temp file on write failure + try: + os.unlink(tmp_path) + except OSError: + pass + raise + except Exception as e: + logger.debug("[plugin_state] write failed: %s", e) + + # ═══════════════════════════════════════════════════════════════════════════ # Pure Function: _format_presence_message # ═══════════════════════════════════════════════════════════════════════════ diff --git a/plugin/archivar/tests/test_presence_engine.py b/plugin/archivar/tests/test_presence_engine.py index fec699c..022c50f 100644 --- a/plugin/archivar/tests/test_presence_engine.py +++ b/plugin/archivar/tests/test_presence_engine.py @@ -1777,3 +1777,59 @@ class TestHoneymoonBusyMinVisible: assert busy_idx < online_idx, ( f"busy (idx={busy_idx}) muss vor online (idx={online_idx}) kommen: {statuses}" ) + + +# ═══════════════════════════════════════════════════════════════════════════ +# P1-2: Plugin-State-Datei — Pfad, atomares Lesen/Schreiben +# ═══════════════════════════════════════════════════════════════════════════ + + +class TestPluginStateFile: + """P1-2: Plugin-State-Datei — Pfad, atomares Lesen/Schreiben.""" + + def test_get_plugin_state_path_default(self): + """_get_plugin_state_path() liefert ~/.hermes/plugin_state/hermes_rocket_plugin.json.""" + from plugin.archivar.presence_engine import _get_plugin_state_path + path = _get_plugin_state_path() + assert path.endswith("hermes_rocket_plugin.json") + assert ".hermes" in path + assert "plugin_state" in path + + def test_read_plugin_state_missing_file(self): + """_read_plugin_state() bei fehlender Datei → {}.""" + from plugin.archivar.presence_engine import _read_plugin_state + result = _read_plugin_state("/tmp/nonexistent_plugin_state.json") + assert result == {} + + def test_read_plugin_state_valid(self, tmp_path): + """_read_plugin_state() liest gültige JSON-Datei.""" + from plugin.archivar.presence_engine import _read_plugin_state + import json + p = tmp_path / "state.json" + p.write_text(json.dumps({"background_tasks": 3, "last_update_iso": "2026-01-01T00:00:00", "source": "plugin_internal", "schema_version": 1})) + result = _read_plugin_state(str(p)) + assert result["background_tasks"] == 3 + assert result["source"] == "plugin_internal" + + def test_read_plugin_state_corrupt_json(self, tmp_path): + """_read_plugin_state() bei korrupter JSON → {} (kein Crash).""" + from plugin.archivar.presence_engine import _read_plugin_state + p = tmp_path / "state.json" + p.write_text("{invalid json") + result = _read_plugin_state(str(p)) + assert result == {} + + def test_write_plugin_state_atomic(self, tmp_path): + """_write_plugin_state() schreibt atomar (temp + rename).""" + from plugin.archivar.presence_engine import _write_plugin_state, _read_plugin_state + import json + p = tmp_path / "state.json" + data = {"background_tasks": 5, "last_update_iso": "2026-01-01T00:00:00", "source": "plugin_internal", "schema_version": 1} + _write_plugin_state(str(p), data) + # Datei existiert + assert p.exists() + # Inhalt korrekt + result = _read_plugin_state(str(p)) + assert result["background_tasks"] == 5 + # Keine .tmp-Datei liegt rum + assert not list(tmp_path.glob("*.tmp"))