feat(p1-2): Plugin-State-Datei — atomare Hilfsfunktionen (_get_plugin_state_path, _read_plugin_state, _write_plugin_state)
This commit is contained in:
@@ -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
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -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"))
|
||||
|
||||
Reference in New Issue
Block a user