diff --git a/config.example.toml b/config.example.toml index 90b27005..5572cb69 100644 --- a/config.example.toml +++ b/config.example.toml @@ -80,3 +80,10 @@ ttl = 86400 # When true, the robot's id, its signature and its request headers are sent to Roborock, along with this server's IP. [matter] key_proxy = false + +# [metrics] +# Optional Prometheus exposition on GET /metrics (disabled by default). +# When enabled, scrapers must send Authorization: Bearer . +# enabled = false +# bearer_token = "replace-with-a-long-random-token" +# bearer_token_file = "/run/secrets/metrics_token" diff --git a/docs/index.md b/docs/index.md index 0d508a6c..ef98a6eb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -23,6 +23,7 @@ If you want to support this project, next time you buy a Roborock, use one of my - [Mobile App Options](roborock_app.md) - [Updating](updating.md) - [Tested vacuums](tested_vacuums.md) +- [Prometheus metrics](metrics.md) - [Reverse proxy](reverse_proxy.md) - [Custom MQTT](custom_mqtt.md) - [Custom certificate management](custom_cert_management.md) diff --git a/docs/metrics.md b/docs/metrics.md new file mode 100644 index 00000000..1cd6f6f2 --- /dev/null +++ b/docs/metrics.md @@ -0,0 +1,70 @@ +# Prometheus Metrics + +The stack can expose an opt-in `GET /metrics` endpoint in Prometheus text format on the same HTTPS listener as the Roborock protocol (`network.https_port`). It is **disabled by default**. + +## When to use it + +Use this when you want alerts such as “vacuum X has not sent MQTT traffic for 15 minutes” without putting the admin password into your monitoring stack or scraping JSON endpoints that include secrets (`local_key`, session material). + +The route works with `--core-only` (standalone admin routes are not required). + +## Configuration + +```toml +[metrics] +enabled = true +bearer_token_file = "/run/secrets/metrics_token" +``` + +Or set `bearer_token` inline. If both are set, the inline value wins. `load_config` requires a token when `enabled = true`. + +Scrapers must send: + +```http +Authorization: Bearer +``` + +### Prometheus scrape example + +```yaml +scrape_configs: + - job_name: roborock-local-server + scheme: https + tls_config: + insecure_skip_verify: false + authorization: + type: Bearer + credentials: your-metrics-token + metrics_path: /metrics + static_configs: + - targets: ["api-roborock.example.com:555"] +``` + +Behind a reverse proxy on port 443, point at the public hostname/port; the server still listens on `https_port` internally. + +## Metrics overview + +Device identity (`duid`, `did`, `name`, `model`) is exported. **Never** exported: `local_key`, protocol auth data, client IPs, or MQTT payload previews. + +| Metric | Notes | +|--------|--------| +| `roborock_device_connected{duid}` | MQTT session flag, or recent MQTT within 180s | +| `roborock_device_last_mqtt_timestamp_seconds{duid}` | Omitted until first MQTT message | +| `roborock_service_up{service}` | Supervisor `running` flags for enabled services | +| `roborock_tls_certificate_expiry_timestamp_seconds` | Only when `listener_mode = "local_tls"` | + +## Suggested alert + +Silence-based MQTT alert (more reliable than `connected` immediately after restart): + +```promql +time() - roborock_device_last_mqtt_timestamp_seconds{duid="your-inventory-duid"} > 900 +``` + +Vacuums that never sent MQTT have no `last_mqtt` series; use `roborock_device_info` or `absent()` for those cases. + +## Limitations + +- `roborock_device_last_mqtt_disconnect_timestamp_seconds` is not persisted across server restarts. +- With `listener_mode = "external_tls"`, the TLS certificate expiry metric is omitted (the proxy holds the certificate). +- `roborock_service_up{service="https_server"}` is 1 on any successful scrape, because the HTTP listener responded. \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index cf26ac8d..782b4b22 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -61,6 +61,7 @@ nav: - Matter: matter.md - Reference: - Log Retention: logging.md + - Prometheus Metrics: metrics.md - Last-Known State: last_known_state.md - Known Limitations: known_limitations.md - Schedule Support (Experimental): schedules.md diff --git a/src/roborock_local_server/certs.py b/src/roborock_local_server/certs.py index 052d3fa6..083d6225 100644 --- a/src/roborock_local_server/certs.py +++ b/src/roborock_local_server/certs.py @@ -33,6 +33,15 @@ class CertificatePaths: _FilesSignature = tuple[tuple[int, int, int], tuple[int, int, int]] +def certificate_expiry_unix_seconds(cert_file: Path) -> float | None: + """Return not_valid_after_utc as a Unix timestamp, or None if the file cannot be parsed.""" + try: + cert = x509.load_pem_x509_certificate(cert_file.read_bytes()) + except Exception: + return None + return cert.not_valid_after_utc.timestamp() + + def validate_certificate_pair(cert_file: Path, key_file: Path) -> None: """Raise if the key does not belong to the certificate or either file cannot be parsed.""" ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) diff --git a/src/roborock_local_server/config.py b/src/roborock_local_server/config.py index 6fb12c5e..8402c1cc 100644 --- a/src/roborock_local_server/config.py +++ b/src/roborock_local_server/config.py @@ -112,6 +112,15 @@ class MatterConfig: key_proxy: bool = False +@dataclass(frozen=True) +class MetricsConfig: + """Optional Prometheus text exposition on GET /metrics.""" + + enabled: bool = False + bearer_token: str = "" + bearer_token_file: str = "" + + @dataclass(frozen=True) class AppConfig: network: NetworkConfig @@ -122,6 +131,7 @@ class AppConfig: turn: TurnConfig = TurnConfig() logging: LoggingConfig = LoggingConfig() matter: MatterConfig = MatterConfig() + metrics: MetricsConfig = MetricsConfig() @dataclass(frozen=True) @@ -142,6 +152,7 @@ class AppPaths: cloudflare_token_file: Path acme_eab_kid_file: Path acme_eab_hmac_key_file: Path + metrics_bearer_token_file: Path cert_file: Path key_file: Path @@ -280,6 +291,7 @@ def load_config(path: str | Path) -> AppConfig: admin = _get_section(parsed, "admin") turn = _get_section(parsed, "turn") matter = _get_section(parsed, "matter") + metrics = _get_section(parsed, "metrics") turn_mode = str(turn.get("mode", "external" if _as_bool(turn.get("enabled"), False) else "disabled")).strip().lower() broker_mode = str(broker.get("mode", "embedded")).strip().lower() if broker_mode not in {"embedded", "external"}: @@ -389,8 +401,20 @@ def load_config(path: str | Path) -> AppConfig: realm=str(turn.get("realm", "") or turn.get("host", "")).strip(), ttl=_as_int(turn.get("ttl"), "turn.ttl", 86400), ), + metrics=MetricsConfig( + enabled=_as_bool(metrics.get("enabled"), False), + bearer_token=str(metrics.get("bearer_token", "")).strip(), + bearer_token_file=str(metrics.get("bearer_token_file", "")).strip(), + ), ) + if config.metrics.enabled and not ( + config.metrics.bearer_token or config.metrics.bearer_token_file + ): + raise ValueError( + "metrics.enabled requires metrics.bearer_token or metrics.bearer_token_file" + ) + if len(config.admin.session_secret) < 24: raise ValueError("admin.session_secret must be at least 24 characters") if "@" not in config.admin.protocol_login_email: @@ -474,6 +498,9 @@ def resolve_paths(config_file: str | Path, config: AppConfig) -> AppPaths: acme_eab_hmac_key_file = Path(config.tls.acme_eab_hmac_key_file or state_dir / "acme_eab_hmac_key") if not acme_eab_hmac_key_file.is_absolute(): acme_eab_hmac_key_file = (config_root / acme_eab_hmac_key_file).resolve() + metrics_bearer_token_file = Path(config.metrics.bearer_token_file or state_dir / "metrics_token") + if not metrics_bearer_token_file.is_absolute(): + metrics_bearer_token_file = (config_root / metrics_bearer_token_file).resolve() return AppPaths( config_file=config_path, @@ -492,6 +519,7 @@ def resolve_paths(config_file: str | Path, config: AppConfig) -> AppPaths: cloudflare_token_file=cloudflare_token_file, acme_eab_kid_file=acme_eab_kid_file, acme_eab_hmac_key_file=acme_eab_hmac_key_file, + metrics_bearer_token_file=metrics_bearer_token_file, cert_file=cert_file, key_file=key_file, ) diff --git a/src/roborock_local_server/metrics.py b/src/roborock_local_server/metrics.py new file mode 100644 index 00000000..2f16ed73 --- /dev/null +++ b/src/roborock_local_server/metrics.py @@ -0,0 +1,170 @@ +"""Prometheus text exposition for stack health and device state.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timezone +import secrets + + +def _iso_to_unix(value: str | None) -> float | None: + if not isinstance(value, str) or not value.strip(): + return None + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + return parsed.astimezone(timezone.utc).timestamp() + + +def _escape_label(value: str) -> str: + escaped: list[str] = [] + for character in str(value or ""): + if character == "\\": + escaped.append("\\\\") + elif character == '"': + escaped.append('\\"') + elif character == "\n": + escaped.append("\\n") + else: + escaped.append(character) + return "".join(escaped) + + +def _label_set(labels: dict[str, str]) -> str: + if not labels: + return "" + parts = [f'{key}="{_escape_label(val)}"' for key, val in sorted(labels.items())] + return "{" + ",".join(parts) + "}" + + +def parse_authorization_bearer(header_value: str | None) -> str | None: + raw = str(header_value or "").strip() + if not raw: + return None + parts = raw.split(None, 1) + if len(parts) != 2 or parts[0].lower() != "bearer": + return None + token = parts[1].strip() + return token or None + + +def bearer_token_valid(provided: str | None, expected: str) -> bool: + expected_clean = str(expected or "").strip() + if not expected_clean: + return False + if provided is None: + return False + provided_clean = provided.strip() + return secrets.compare_digest( + provided_clean.encode("utf-8"), + expected_clean.encode("utf-8"), + ) + + +@dataclass(frozen=True) +class MetricsDeviceRow: + duid: str + did: str + name: str + model: str + connected: bool + public_key_ready: bool + last_mqtt_at: str = "" + last_disconnect_at: str = "" + last_http_at: str = "" + + +@dataclass +class MetricsSnapshot: + version: str + services: list[dict[str, object]] = field(default_factory=list) + active_mqtt_connections: int = 0 + new_connections_enabled: bool = True + protocol_auth_enabled: bool = True + devices_pending_mqtt_recovery: int = 0 + tls_certificate_expiry_timestamp_seconds: float | None = None + devices: list[MetricsDeviceRow] = field(default_factory=list) + + +def _line(metric: str, value: int | float, labels: dict[str, str] | None = None) -> str: + suffix = _label_set(labels or {}) + if isinstance(value, float) and value.is_integer(): + value = int(value) + return f"{metric}{suffix} {value}" + + +def render_prometheus(snap: MetricsSnapshot) -> str: + lines: list[str] = [] + + def add_family(help_text: str, metric_type: str, metric_name: str) -> None: + lines.append(f"# HELP {metric_name} {help_text}") + lines.append(f"# TYPE {metric_name} {metric_type}") + + add_family("Build version", "gauge", "roborock_build_info") + lines.append(_line("roborock_build_info", 1, {"version": snap.version})) + + add_family("Whether a stack service is running (enabled services only)", "gauge", "roborock_service_up") + for service in snap.services: + if not service.get("enabled"): + continue + name = str(service.get("name") or "").strip() + if not name: + continue + running = 1 if service.get("running") else 0 + lines.append(_line("roborock_service_up", running, {"service": name})) + + add_family("Active MQTT TLS proxy connections", "gauge", "roborock_mqtt_active_connections") + lines.append(_line("roborock_mqtt_active_connections", snap.active_mqtt_connections)) + + add_family("Whether new vacuum connections are allowed", "gauge", "roborock_new_connections_enabled") + lines.append(_line("roborock_new_connections_enabled", 1 if snap.new_connections_enabled else 0)) + + add_family("Whether protocol login auth is required", "gauge", "roborock_protocol_auth_enabled") + lines.append(_line("roborock_protocol_auth_enabled", 1 if snap.protocol_auth_enabled else 0)) + + add_family("Devices with known MQTT username but no stored password", "gauge", "roborock_devices_pending_mqtt_recovery") + lines.append(_line("roborock_devices_pending_mqtt_recovery", snap.devices_pending_mqtt_recovery)) + + if snap.tls_certificate_expiry_timestamp_seconds is not None: + add_family("TLS certificate notAfter (local TLS listener only)", "gauge", "roborock_tls_certificate_expiry_timestamp_seconds") + lines.append( + _line( + "roborock_tls_certificate_expiry_timestamp_seconds", + snap.tls_certificate_expiry_timestamp_seconds, + ) + ) + + add_family("Device identity labels", "gauge", "roborock_device_info") + add_family("MQTT session or recent MQTT activity", "gauge", "roborock_device_connected") + add_family("Last MQTT message time", "gauge", "roborock_device_last_mqtt_timestamp_seconds") + add_family("Last MQTT disconnect time", "gauge", "roborock_device_last_mqtt_disconnect_timestamp_seconds") + add_family("Last HTTP request time", "gauge", "roborock_device_last_http_timestamp_seconds") + add_family("Onboarding public key ready", "gauge", "roborock_device_public_key_ready") + + for device in snap.devices: + duid = str(device.duid or "").strip() + if not duid: + continue + duid_label = {"duid": duid} + info_labels = { + "duid": duid, + "did": str(device.did or "").strip(), + "name": str(device.name or "").strip(), + "model": str(device.model or "").strip(), + } + lines.append(_line("roborock_device_info", 1, info_labels)) + lines.append(_line("roborock_device_connected", 1 if device.connected else 0, duid_label)) + lines.append(_line("roborock_device_public_key_ready", 1 if device.public_key_ready else 0, duid_label)) + + last_mqtt = _iso_to_unix(device.last_mqtt_at) + if last_mqtt is not None: + lines.append(_line("roborock_device_last_mqtt_timestamp_seconds", last_mqtt, duid_label)) + last_disconnect = _iso_to_unix(device.last_disconnect_at) + if last_disconnect is not None: + lines.append(_line("roborock_device_last_mqtt_disconnect_timestamp_seconds", last_disconnect, duid_label)) + last_http = _iso_to_unix(device.last_http_at) + if last_http is not None: + lines.append(_line("roborock_device_last_http_timestamp_seconds", last_http, duid_label)) + + return "\n".join(lines) + "\n" \ No newline at end of file diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 157e3bea..3f5a0d13 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -23,7 +23,15 @@ import uvicorn from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware -from .certs import CertificateManager +from . import __version__ +from .certs import CertificateManager, certificate_expiry_unix_seconds +from .metrics import ( + MetricsDeviceRow, + MetricsSnapshot, + bearer_token_valid, + parse_authorization_bearer, + render_prometheus, +) from .bundled_backend.shared.constants import DEFAULT_PRODUCT_SCHEMA, region_country from .bundled_backend.shared.data_helpers import utcnow_iso from .product_registry import resolve_product_metadata @@ -1957,7 +1965,64 @@ def _is_standalone_route_path(path: str) -> bool: normalized = str(path or "").rstrip("/") return normalized == "/admin" or normalized.startswith("/admin/") + def _read_metrics_bearer_token_file(self) -> str: + path = self.paths.metrics_bearer_token_file + if not path.exists(): + return "" + return path.read_text(encoding="utf-8").strip() + + def _resolve_metrics_bearer_token(self) -> str: + inline = str(self.config.metrics.bearer_token or "").strip() + if inline: + return inline + return self._read_metrics_bearer_token_file() + + def _build_metrics_snapshot(self) -> MetricsSnapshot: + self._refresh_turn_health() + health = self.runtime_state.health_snapshot() + vacuums = self._vacuums_payload()["vacuums"] + devices: list[MetricsDeviceRow] = [] + for vac in vacuums: + onboarding = dict(vac.get("onboarding") or {}) + devices.append( + MetricsDeviceRow( + duid=str(vac.get("duid") or "").strip(), + did=str(vac.get("did") or "").strip(), + name=str(vac.get("name") or "").strip(), + model=str(vac.get("model") or "").strip(), + connected=bool(vac.get("connected")), + public_key_ready=bool(onboarding.get("public_key_ready")), + last_mqtt_at=str(vac.get("last_mqtt_at") or "").strip(), + last_disconnect_at=str(vac.get("last_disconnect_at") or "").strip(), + last_http_at=str(vac.get("last_http_at") or "").strip(), + ) + ) + tls_expiry: float | None = None + if self.config.network.listener_mode == "local_tls": + tls_expiry = certificate_expiry_unix_seconds(self.paths.cert_file) + return MetricsSnapshot( + version=__version__, + services=[dict(item) for item in (health.get("services") or []) if isinstance(item, dict)], + active_mqtt_connections=int(health.get("active_mqtt_connections") or 0), + new_connections_enabled=bool(self.config.admin.new_connections_enabled), + protocol_auth_enabled=bool(self.config.admin.protocol_auth_enabled), + devices_pending_mqtt_recovery=len(self.runtime_credentials.recovery_pending_devices()), + tls_certificate_expiry_timestamp_seconds=tls_expiry, + devices=devices, + ) + def _register_protocol_routes(self, app: FastAPI) -> None: + if self.config.metrics.enabled: + + @app.get("/metrics") + async def metrics_endpoint(request: Request) -> Response: + expected = self._resolve_metrics_bearer_token() + provided = parse_authorization_bearer(request.headers.get("authorization")) + if not bearer_token_valid(provided, expected): + return Response(status_code=401) + body = render_prometheus(self._build_metrics_snapshot()) + return Response(content=body, media_type="text/plain; version=0.0.4; charset=utf-8") + @app.get("/ui/api/health") async def ui_health(request: Request) -> JSONResponse: if not self.enable_standalone_admin: diff --git a/tests/test_config.py b/tests/test_config.py index ba569588..811c701b 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,6 +6,32 @@ from roborock_local_server.config import load_config, resolve_paths +def test_metrics_defaults_and_validation(tmp_path: Path) -> None: + path = write_release_config(tmp_path) + defaults = load_config(path).metrics + assert defaults.enabled is False + assert defaults.bearer_token == "" + assert defaults.bearer_token_file == "" + + config = load_config(path) + paths = resolve_paths(path, config) + assert paths.metrics_bearer_token_file == (tmp_path / "data" / "state" / "metrics_token").resolve() + + path.write_text(path.read_text() + '\n[metrics]\nenabled = true\n') + with pytest.raises(ValueError, match="metrics.enabled requires"): + load_config(path) + + path.write_text( + path.read_text().replace( + '\n[metrics]\nenabled = true\n', + '\n[metrics]\nenabled = true\nbearer_token_file = "secrets/metrics_token"\n', + ) + ) + config = load_config(path) + paths = resolve_paths(path, config) + assert paths.metrics_bearer_token_file == (tmp_path / "secrets" / "metrics_token").resolve() + + def test_logging_defaults_and_overrides(tmp_path): path = write_release_config(tmp_path) defaults = load_config(path).logging diff --git a/tests/test_metrics.py b/tests/test_metrics.py new file mode 100644 index 00000000..14c076bc --- /dev/null +++ b/tests/test_metrics.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone +from pathlib import Path + +from fastapi.testclient import TestClient + +from conftest import write_release_config +from roborock_local_server import __version__ +from roborock_local_server.config import load_config, resolve_paths +from roborock_local_server.metrics import ( + MetricsDeviceRow, + MetricsSnapshot, + bearer_token_valid, + render_prometheus, +) +from roborock_local_server.server import ReleaseSupervisor +from test_certs import _write_certificate + + +METRICS_TOKEN = "metrics-test-bearer-token-0123456789" + + +def test_bearer_token_valid_non_ascii_does_not_raise() -> None: + assert bearer_token_valid("wrông", METRICS_TOKEN) is False + + +def _append_metrics_config(config_path: Path, *, token: str = METRICS_TOKEN) -> None: + config_path.write_text( + config_path.read_text() + + f'\n[metrics]\nenabled = true\nbearer_token = "{token}"\n', + encoding="utf-8", + ) + + +def _seed_inventory(supervisor: ReleaseSupervisor, *, local_key: str = "super-secret-local-key") -> None: + paths = supervisor.paths + paths.inventory_path.parent.mkdir(parents=True, exist_ok=True) + paths.inventory_path.write_text( + json.dumps( + { + "devices": [ + { + "duid": "inventory-s7-duid", + "did": "1103811971559", + "name": "S7", + "model": "roborock.vacuum.a15", + "local_key": local_key, + } + ] + } + ) + + "\n", + encoding="utf-8", + ) + paths.runtime_credentials_path.parent.mkdir(parents=True, exist_ok=True) + paths.runtime_credentials_path.write_text( + json.dumps( + { + "schema_version": 2, + "devices": [ + { + "did": "1103811971559", + "duid": "inventory-s7-duid", + "name": "S7", + "model": "roborock.vacuum.a15", + "device_mqtt_usr": "dd211305e2d4873b", + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + supervisor.refresh_inventory_state() + supervisor.runtime_state.record_mqtt_connection( + conn_id="metrics-conn", + client_ip="192.168.1.50", + client_port=1883, + ) + supervisor.runtime_state.record_mqtt_message( + conn_id="metrics-conn", + direction="c2b", + topic="rr/d/i/1103811971559/dd211305e2d4873b", + payload_preview="{}", + ) + + +def test_metrics_disabled_uses_catchall(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path) + supervisor = ReleaseSupervisor(config=load_config(config_file), paths=resolve_paths(config_file, load_config(config_file))) + client = TestClient(supervisor.app) + + response = client.get("/metrics") + assert response.status_code == 200 + assert response.json()["data"] == {"ok": True, "route": "/metrics"} + assert "# TYPE" not in response.text + + +def test_metrics_auth_and_success(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path) + _append_metrics_config(config_file) + config = load_config(config_file) + supervisor = ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)) + _seed_inventory(supervisor, local_key="do-not-leak-this-key") + client = TestClient(supervisor.app) + + assert client.get("/metrics").status_code == 401 + assert client.get("/metrics", headers={"Authorization": "Bearer wrong"}).status_code == 401 + + response = client.get("/metrics", headers={"Authorization": f"Bearer {METRICS_TOKEN}"}) + assert response.status_code == 200 + assert response.headers["content-type"].startswith("text/plain") + body = response.text + assert f'roborock_build_info{{version="{__version__}"}} 1' in body + assert "do-not-leak-this-key" not in body + assert config.admin.session_secret not in body + assert 'duid="inventory-s7-duid"' in body + assert "roborock_device_last_mqtt_timestamp_seconds" in body + + +def test_metrics_works_in_core_only_mode(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path) + _append_metrics_config(config_file) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + supervisor = ReleaseSupervisor(config=config, paths=paths, enable_standalone_admin=False) + client = TestClient(supervisor.app) + + assert client.get("/ui/api/health").status_code == 404 + assert client.get("/metrics", headers={"Authorization": f"Bearer {METRICS_TOKEN}"}).status_code == 200 + + +def test_render_prometheus_escapes_labels_and_skips_empty_timestamps() -> None: + snap = MetricsSnapshot( + version="1.0.0", + devices=[ + MetricsDeviceRow( + duid="duid-1", + did='did"1', + name="Room\nA", + model="roborock.vacuum.test", + connected=True, + public_key_ready=False, + last_mqtt_at="", + last_disconnect_at="", + last_http_at="2026-01-15T12:00:00+00:00", + ) + ], + ) + body = render_prometheus(snap) + assert 'name="Room\\nA"' in body + assert 'did="did\\"1"' in body + assert "roborock_device_last_mqtt_timestamp_seconds{duid=" not in body + assert "roborock_device_last_http_timestamp_seconds{duid=" in body + + +def test_tls_expiry_metric_local_tls(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path) + _append_metrics_config(config_file) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + _write_certificate(paths.cert_file, common_name="metrics.example", san_names=["metrics.example"]) + expected_expiry = datetime.now(timezone.utc) + timedelta(days=30) + supervisor = ReleaseSupervisor(config=config, paths=paths) + client = TestClient(supervisor.app) + response = client.get("/metrics", headers={"Authorization": f"Bearer {METRICS_TOKEN}"}) + assert response.status_code == 200 + line = next( + line + for line in response.text.splitlines() + if line.startswith("roborock_tls_certificate_expiry_timestamp_seconds ") + ) + exported = float(line.rsplit(" ", 1)[-1]) + assert abs(exported - expected_expiry.timestamp()) < 3600 + + +def test_tls_expiry_metric_omitted_for_external_tls(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path, listener_mode="external_tls") + _append_metrics_config(config_file) + config = load_config(config_file) + supervisor = ReleaseSupervisor(config=config, paths=resolve_paths(config_file, config)) + client = TestClient(supervisor.app) + response = client.get("/metrics", headers={"Authorization": f"Bearer {METRICS_TOKEN}"}) + assert "roborock_tls_certificate_expiry_timestamp_seconds" not in response.text + + +def test_recovery_pending_gauge(tmp_path: Path) -> None: + config_file = write_release_config(tmp_path) + _append_metrics_config(config_file) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + paths.runtime_credentials_path.parent.mkdir(parents=True, exist_ok=True) + paths.runtime_credentials_path.write_text( + json.dumps( + { + "schema_version": 2, + "devices": [ + { + "did": "1103811971559", + "duid": "inventory-s7-duid", + "device_mqtt_usr": "mqtt-user", + "device_mqtt_pass": "", + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + supervisor = ReleaseSupervisor(config=config, paths=paths) + client = TestClient(supervisor.app) + response = client.get("/metrics", headers={"Authorization": f"Bearer {METRICS_TOKEN}"}) + assert "roborock_devices_pending_mqtt_recovery 1" in response.text \ No newline at end of file