коррекции неудачных тестов

This commit is contained in:
Ilgiz Kalmetyev 2026-04-13 15:32:48 +05:00
parent dabfe98438
commit c932ecfcdc
130 changed files with 3676 additions and 2277 deletions

View File

@ -0,0 +1,12 @@
app_env = "test"
database_dsn = "sqlite+aiosqlite:///C:/p - wf-agent/.tmp/pytest/wf-agent-test-runtime.sqlite3"
outbox_database_dsn = "sqlite+aiosqlite:///C:/p - wf-agent/.tmp/pytest/wf-agent-test-runtime-outbox.sqlite3"
wifi_interface_name = "wlan0"
cache_ttl_seconds = 3600
history_ttl_seconds = 7200
[[transports]]
name = "default"
kind = "none"
enabled = true
period_seconds = 60

Binary file not shown.

152
README.md
View File

@ -1,156 +1,112 @@
# wf-agent
`wf-agent` - Linux/Python агент для сбора Wi-Fi телеметрии, journald-событий, координат и выполнения команд.
Проект спроектирован как модульный монолит на Python 3.12+ с `asyncio`, FastAPI и асинхронным слоем хранения на SQLAlchemy 2.x. Основной принцип работы - сначала сохранить данные локально, затем доставлять их наружу через отдельный слой экспорта.
`wf-agent` - Linux/Python агент для сбора Wi-Fi телеметрии, событий journald, координат и выполнения команд. Проект построен как модульный монолит на Python 3.12+ с `asyncio`, FastAPI, SQLite и SQLAlchemy 2.x.
## Назначение
`wf-agent` нужен, чтобы:
Агент нужен, чтобы:
- собирать данные из нескольких источников на Linux-хосте;
- нормализовать входные события в каноническую модель;
- нормализовать сырые события в каноническую модель;
- хранить latest state и event log отдельно;
- сохранять персистентный journal cursor;
- исполнять команды через командный сервис и D-Bus executor;
- доставлять часть данных немедленно, часть - пакетно по расписанию;
- экспортировать закешированные сообщения через транспортно-ориентированный pipeline;
- строить корреляции между Wi-Fi, журналом, координатами и командами;
- сохранять cursor `systemd-journal` и другие служебные состояния;
- выполнять команды через command service и D-Bus executor;
- экспортировать часть данных сразу, часть по расписанию;
- строить корреляции между Wi-Fi, journald, координатами и командами;
- предоставлять HTTP API, CLI, метрики и операционные runbooks.
## Что делает проект
Источники данных:
- `wpa_supplicant` по system D-Bus;
- `systemd-journal`;
- навигационный источник координат.
Дальше поток выглядит так:
`adapter -> internal envelope -> validation -> normalization -> canonical model -> persistence -> delivery overlay -> transport outbox -> northbound/API/observability`
Для закешированных сообщений доставка теперь определяется транспортом:
- `[[transports]]` задаёт список outbound transport definitions;
- транспорт `default` обязателен и используется как fallback для cached deliveries;
- в ACL правило может явно указать `transport <name>`;
- `kind = "none"` не создаёт пакет и помечает due-сообщения как `delivered`;
- `kind = "webhook"` собирает JSON packet и отправляет его наружу.
## Архитектура
### Поток данных
```text
adapter -> internal envelope -> validation -> normalization -> canonical model -> persistence -> delivery overlay -> transport outbox -> northbound/API/observability
```
### Основные принципы
- модульный монолит, а не набор микросервисов;
- все входящие данные проходят путь `raw envelope -> validation -> normalization`;
- весь входящий поток проходит `raw envelope -> validation -> normalization`;
- сначала persist, потом send;
- слой кеширования не знает о транспортной механике и хранит данные как аккумулятор;
- слой кеширования не знает о транспортах и служит аккумулирующим storage;
- delivery state хранится отдельно от `cached_events`;
- outbox pattern обязателен для доставляемых сущностей;
- есть отдельный outbox database для packet state и counters;
- API не вызывает adapters напрямую, а работает через services;
- adapters не пишут прямо во внешние системы;
- транспортный outbox хранится в отдельной SQLite БД;
- API не вызывает adapters напрямую, только services;
- timestamps всегда UTC-aware;
- latest state и event log разделены;
- journal cursor хранится персистентно;
- команды управляются через command service и state machine;
- тесты не должны использовать production-like БД.
- тесты не должны использовать production-like DSN.
### Поток обработки
### Экспорт кешированных сообщений
1. Adapter получает сырой сигнал от источника.
2. Envelope попадает во внутренний dispatcher.
3. Validator проверяет обязательные поля и форму.
4. Canonical mapper превращает envelope в каноническую запись.
5. Delivery classifier назначает `delivery_mode` и `priority`.
6. Canonical ingestion service сохраняет запись в storage.
7. Outbox service создаёт запись доставки, если это нужно.
8. Cached export worker выбирает due rows по transport schedule.
9. Packet outbox хранит JSON packet до успешной отправки или уничтожения.
10. Correlation layer связывает Wi-Fi, журнал, координаты и команды.
11. Derived events попадают в ту же persistence/delivery модель.
Кешированные сообщения экспортируются по transport schedule:
## Компоненты и связи
- `[[transports]]` задаёт outbound transports;
- transport `default` обязателен и используется как fallback для cached deliveries;
- в ACL можно указать `transport <name>` для конкретного правила;
- `kind = "none"` не создаёт packet и помечает due-сообщения как `delivered`;
- `kind = "webhook"` собирает JSON packet и отправляет его наружу.
## Компоненты
### `app.adapters`
Source adapters работают только с источниками:
- `navigation` читает координаты и формирует navigation envelopes;
- `journal` читает `systemd-journal` с persistent cursor;
- `dbus_wpa` подключается к system D-Bus, получает сигналы `wpa_supplicant` и исполняет D-Bus команды;
- `dbus_wpa.client` и `navigation.client` содержат test-friendly abstractions и fake clients.
Adapters не пишут в БД напрямую и не отправляют данные northbound.
- `dbus_wpa` подключается к system D-Bus, получает сигналы `wpa_supplicant` и выполняет D-Bus команды;
- client-модули содержат test-friendly абстракции и fake clients.
### `app.ingestion`
Этот слой связывает adapters с внутренним потоком:
- `IngestionDispatcher` маршрутизирует envelopes по каналам;
- `SourceManager` управляет жизненным циклом adapters и health state;
- queues используются как внутренняя транспортная прослойка между source runtime и services.
- queues служат внутренней транспортной прослойкой между source runtime и services.
### `app.normalization`
Пакет отвечает за формальное приведение raw envelope к каноническому виду:
- `validator` проверяет входную форму;
- `validator` проверяет форму входных данных;
- `mapper` создаёт canonical records;
- `classifier` назначает delivery mode и priority;
- `dedup` даёт keys и idempotency helpers.
- `dedup` содержит dedup и idempotency helpers.
### `app.services`
Services владеют business orchestration:
- `CanonicalIngestionService` выполняет `validate -> map -> classify -> persist`;
- `StateService` и `EventService` разделяют latest-state и event-log persistence;
- `OutboxService` создаёт transactional outbox rows для доставляемых сущностей;
- `ReplayService` управляет retry и replay абстракциями;
- `ReplayService` управляет retry/replay абстракциями;
- `CommandService` и command state machine управляют жизненным циклом команд.
### `app.correlation`
Correlation layer не пишет в storage и не ходит в adapters:
- `LocationMatcher` связывает Wi-Fi event с ближайшей valid location snapshot;
- `LocationMatcher` связывает Wi-Fi event с ближайшей валидной location snapshot;
- `JournalLinker` связывает Wi-Fi event с journal evidence;
- `CommandLinker` связывает command с observed effects;
- `DerivedEventEngine` превращает корреляции в canonical derived events.
- `DerivedEventEngine` превращает корреляции в derived events.
### `app.delivery`
Delivery layer построен поверх northbound client abstraction:
- `NorthboundExporter` превращает outbox row в стабильный payload;
- `CachedMessagePacketBuilder` собирает JSON packet для cached exports;
- packet builder собирает JSON packet для cached exports;
- `WebhookTransportClient` отправляет packet наружу;
- `FakeNorthboundClient` используется в тестах;
- retry/dead-letter helpers управляют ошибками доставки для других northbound flows.
- `FakeNorthboundClient` используется в тестах.
### `app.workers`
Worker layer исполняет фоновые циклы:
- `CachedExportWorker` обрабатывает cached messages по transport schedule;
- `SourceHealthWorker` записывает health snapshots;
- `SourceHealthWorker` пишет health snapshots;
- retention worker очищает просроченные cached rows.
### `app.api`
API слой не вызывает adapters напрямую:
- `/health/live` и `/health/ready`;
- `/admin/sources` и `/admin/outbox`;
- `/commands` и command detail/retry endpoints;
- `/admin/sources`, `/admin/outbox`, `/admin/cache-retention`, `/admin/scan-results`;
- `/commands` и retry endpoints;
- `/metrics`.
### `app.cli`
CLI предназначен для локальной диагностики и операторских действий:
- `show messages list`;
- `show messages content`;
- `show outbox state`;
@ -158,20 +114,10 @@ CLI предназначен для локальной диагностики и
- `show outbox counters`;
- `inspect outbox` как alias к `show outbox state`;
- `clear outbox`;
- `clear outbox-counters`.
### `app.monitoring`
Мониторинг отвечает за наблюдаемость:
- counters/gauges для ingestion, delivery и commands;
- `SourceHealthWorker` записывает health snapshots;
- structured logging carries correlation ids and operational context.
- `clear outbox counters`.
### `app.storage`
Storage layer содержит:
- main DB bootstrap;
- outbox DB bootstrap;
- ORM schema;
@ -186,7 +132,7 @@ wf-agent/
app/
adapters/ # navigation, journal, dbus_wpa adapters and client abstractions
api/ # FastAPI entrypoint, health/admin/command/metrics routes
bootstrap/ # application factory, container, lifecycle wiring
bootstrap/ # application factory, dependency wiring, lifecycle
cli/ # local diagnostic CLI
commands/ # command state machine and dispatcher
correlation/ # location matcher, journal linker, command linker, derived events
@ -200,7 +146,6 @@ wf-agent/
workers/ # cached export worker, source health worker, retention worker
deployment/
config/ # example runtime config files, including ACL and transports
env/ # example environment files
systemd/ # systemd service unit baseline
docs/
adr/ # architecture decision records
@ -214,16 +159,18 @@ wf-agent/
## Конфигурация
Ключевые параметры в `wf-agent.toml`:
Основной пример конфига: [deployment/config/wf-agent.toml.example](deployment/config/wf-agent.toml.example)
- `database_dsn` - main SQLite database;
- `outbox_database_dsn` - separate SQLite database for transport outbox;
Ключевые параметры:
- `database_dsn` - основная SQLite база;
- `outbox_database_dsn` - отдельная SQLite база для packet outbox;
- `wifi_interface_name` - целевой Wi-Fi интерфейс;
- `[acl]` - ACL для journal/dbus ingress;
- `[[transports]]` - список outbound transports;
- transport `default` - обязательный fallback для cached deliveries.
Пример рабочей конфигурации см. в [deployment/config/wf-agent.toml.example](deployment/config/wf-agent.toml.example).
Для systemd deployment используется [deployment/systemd/wf-agent.service](deployment/systemd/wf-agent.service).
## Документация
@ -231,7 +178,6 @@ wf-agent/
- [Procedures](docs/operations/procedures.md)
- [Support Guide](docs/operations/support.md)
- [Delivery Policies](docs/architecture/delivery-policies.md)
- [Content Delivery](docs/content-delivery.md)
- [ADR-001: Modular Monolith](docs/adr/ADR-001-modular-monolith.md)
- [ADR-002: SQLite as Persistent Store](docs/adr/ADR-002-postgresql-as-persistent-store.md)
- [ADR-003: Outbox Pattern](docs/adr/ADR-003-outbox-pattern.md)
@ -246,7 +192,7 @@ pip install -e .[test]
pytest -q
```
Для локальной диагностики используйте:
Локальные команды:
```bash
wf-agent --config-file /etc/wf-agent/wf-agent.toml show messages list

View File

@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
import copy
import inspect
import logging
from collections.abc import Sequence
@ -10,7 +9,7 @@ from types import MappingProxyType
from typing import Any, Awaitable, Callable, Mapping, Protocol, runtime_checkable
from app.adapters.base import SourceHealthReporter
from app.adapters.dbus_wpa.health import DbusHealthSnapshot, build_health_details
from app.adapters.dbus_wpa.health import build_health_details
from app.domain.enums import SourceStatus
logger = logging.getLogger(__name__)

View File

@ -18,7 +18,12 @@ from app.core.logging import build_log_context
from app.domain.enums import SourceStatus
from app.domain.value_objects import SourceId, UtcTimestamp
from app.ingestion.dispatcher import IngestionDispatcher
from app.storage.repositories import CachedEventRecord, CachedEventRepository, JournalCursorRecord, JournalCursorRepository
from app.storage.repositories import (
CachedEventRecord,
CachedEventRepository,
JournalCursorRecord,
JournalCursorRepository,
)
from .filters import JournalFilter
from .parser import JournalEntryParser, JournalReading
@ -98,9 +103,9 @@ class JournalAdapter(SourceAdapterProtocol):
{
"source_key": self.source_key,
"ingestion_channel": self.ingestion_channel,
"cursor": None
if self._current_cursor is None
else self._current_cursor.value,
"cursor": (
None if self._current_cursor is None else self._current_cursor.value
),
},
)
logger.info(
@ -110,9 +115,9 @@ class JournalAdapter(SourceAdapterProtocol):
source_key=self.source_key,
channel=self.ingestion_channel,
status=SourceStatus.HEALTHY.value,
cursor=None
if self._current_cursor is None
else self._current_cursor.value,
cursor=(
None if self._current_cursor is None else self._current_cursor.value
),
),
)
self._task = asyncio.create_task(
@ -161,7 +166,11 @@ class JournalAdapter(SourceAdapterProtocol):
"journal poll starting",
extra={
"source_key": self.source_key,
"cursor": None if journal_filter.cursor is None else journal_filter.cursor.value,
"cursor": (
None
if journal_filter.cursor is None
else journal_filter.cursor.value
),
"batch_size": self.batch_size,
"filter": journal_filter.to_dict(),
},
@ -338,9 +347,11 @@ class JournalAdapter(SourceAdapterProtocol):
expires_at=expires_at,
payload=dict(envelope.body),
acl={} if decision is None else decision.to_dict(),
mark=None
if decision is None or decision.rule is None
else decision.rule.scope,
mark=(
None
if decision is None or decision.rule is None
else decision.rule.scope
),
transport_name=transport_name,
)
)

View File

@ -20,7 +20,7 @@ class JournalReaderProtocol(Protocol):
class SystemJournalReader(JournalReaderProtocol):
def __init__(self, *, command: str = 'journalctl', encoding: str = 'utf-8') -> None:
def __init__(self, *, command: str = "journalctl", encoding: str = "utf-8") -> None:
self.command = command
self.encoding = encoding
@ -30,7 +30,11 @@ class SystemJournalReader(JournalReaderProtocol):
command = self._build_command(journal_filter)
logger.debug(
"reading journal batch",
extra={"command": command, "limit": limit, "filter": journal_filter.to_dict()},
extra={
"command": command,
"limit": limit,
"filter": journal_filter.to_dict(),
},
)
try:
process = await asyncio.create_subprocess_exec(
@ -39,7 +43,7 @@ class SystemJournalReader(JournalReaderProtocol):
stderr=asyncio.subprocess.PIPE,
)
except FileNotFoundError as exc:
raise RuntimeError('journalctl command not found') from exc
raise RuntimeError("journalctl command not found") from exc
entries: list[RawJournalEntry] = []
reached_limit = False
@ -51,8 +55,8 @@ class SystemJournalReader(JournalReaderProtocol):
line = await process.stdout.readline()
if not line:
break
text = line.decode(self.encoding, errors='replace').strip()
if not text.startswith('{'):
text = line.decode(self.encoding, errors="replace").strip()
if not text.startswith("{"):
continue
try:
entry = json.loads(text)
@ -75,27 +79,35 @@ class SystemJournalReader(JournalReaderProtocol):
if not reached_limit and process.returncode not in (0, None):
stderr = await process.stderr.read()
message = stderr.decode(self.encoding, errors='replace').strip()
raise RuntimeError(message or 'journalctl invocation failed')
message = stderr.decode(self.encoding, errors="replace").strip()
raise RuntimeError(message or "journalctl invocation failed")
return entries
def _build_command(self, journal_filter: JournalFilter) -> list[str]:
command = [self.command, '--no-pager', '--output=json', '--show-cursor']
command = [self.command, "--no-pager", "--output=json", "--show-cursor"]
if journal_filter.cursor is not None:
command.extend(['--after-cursor', journal_filter.cursor.value])
command.extend(["--after-cursor", journal_filter.cursor.value])
elif journal_filter.since is not None:
command.extend(['--since', str(journal_filter.since)])
command.extend(["--since", str(journal_filter.since)])
else:
command.extend(['--since', 'now'])
command.extend(["--since", "now"])
if journal_filter.until is not None:
command.extend(['--until', str(journal_filter.until)])
command.extend(["--until", str(journal_filter.until)])
logger.debug(
"built journalctl command",
extra={
"command": command,
"cursor": None if journal_filter.cursor is None else journal_filter.cursor.value,
"since": None if journal_filter.since is None else str(journal_filter.since),
"until": None if journal_filter.until is None else str(journal_filter.until),
"cursor": (
None
if journal_filter.cursor is None
else journal_filter.cursor.value
),
"since": (
None if journal_filter.since is None else str(journal_filter.since)
),
"until": (
None if journal_filter.until is None else str(journal_filter.until)
),
},
)
return command
@ -122,7 +134,7 @@ class SystemJournalReader(JournalReaderProtocol):
def _matches_any_name(
self, entry: Mapping[str, Any], names: tuple[str, ...]
) -> bool:
candidate_fields = ('_COMM', 'SYSLOG_IDENTIFIER', 'process_name', 'process')
candidate_fields = ("_COMM", "SYSLOG_IDENTIFIER", "process_name", "process")
for field_name in candidate_fields:
value = entry.get(field_name)
if not isinstance(value, str):
@ -133,4 +145,4 @@ class SystemJournalReader(JournalReaderProtocol):
return False
__all__ = ['JournalReaderProtocol', 'RawJournalEntry', 'SystemJournalReader']
__all__ = ["JournalReaderProtocol", "RawJournalEntry", "SystemJournalReader"]

View File

@ -34,9 +34,11 @@ class NavigationEnvelopeMapper:
timestamp = received_at if received_at is not None else self.clock.now()
return IngestionEnvelope(
channel="navigation",
received_at=UtcTimestamp.from_value(timestamp)
if not isinstance(timestamp, UtcTimestamp)
else timestamp,
received_at=(
UtcTimestamp.from_value(timestamp)
if not isinstance(timestamp, UtcTimestamp)
else timestamp
),
correlation=context,
body=reading.to_body(),
transport_name=transport_name,

View File

@ -145,15 +145,16 @@ async def _load_scan_snapshots(session) -> ScanSnapshotList: # type: ignore[no-
items = [
item
for snapshot in snapshots
if (item := _scan_snapshot_record_from_row(
snapshot, source_map.get(snapshot.to_dict()["source_id"])
)) is not None
if (
item := _scan_snapshot_record_from_row(
snapshot, source_map.get(snapshot.to_dict()["source_id"])
)
)
is not None
]
return ScanSnapshotList(items=items, count=len(items))
def _cache_retention_record_from_row(row) -> CacheRetentionRecord: # type: ignore[no-untyped-def]
return CacheRetentionRecord(
source_id=str(row.source_id),
@ -248,9 +249,11 @@ async def get_source(request: Request, source_key: str) -> SourceInspectionRecor
health_row = health_result.mappings().first()
return _source_record_from_row(
dict(row),
health=None
if health_row is None
else _source_health_from_row(dict(health_row)),
health=(
None
if health_row is None
else _source_health_from_row(dict(health_row))
),
)
@ -304,10 +307,13 @@ async def get_scan_result(request: Request, source_key: str) -> ScanSnapshotReco
raise HTTPException(
status_code=http_status.HTTP_404_NOT_FOUND, detail="source not found"
)
snapshot = await WifiScanSnapshotRepository(session).get_by_source_key(source_key)
snapshot = await WifiScanSnapshotRepository(session).get_by_source_key(
source_key
)
if snapshot is None:
raise HTTPException(
status_code=http_status.HTTP_404_NOT_FOUND, detail="scan snapshot not found"
status_code=http_status.HTTP_404_NOT_FOUND,
detail="scan snapshot not found",
)
return _scan_snapshot_record_from_row(snapshot, dict(source_row))

View File

@ -23,14 +23,16 @@ from .metrics import metrics_router
async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
owns_bootstrap = False
owns_outbox_bootstrap = False
runtime = getattr(app.state, 'runtime', None)
settings = getattr(app.state, 'settings', None)
bootstrap = getattr(app.state, 'bootstrap', None)
outbox_bootstrap = getattr(app.state, 'outbox_bootstrap', None)
runtime = getattr(app.state, "runtime", None)
settings = getattr(app.state, "settings", None)
bootstrap = getattr(app.state, "bootstrap", None)
outbox_bootstrap = getattr(app.state, "outbox_bootstrap", None)
start_runtime = bootstrap is None or settings is not None
try:
if settings is None and bootstrap is None:
settings = load_settings()
app.state.settings = settings
start_runtime = True
if settings is not None:
configure_json_logging(level=settings.log_level)
if bootstrap is None:
@ -49,11 +51,11 @@ async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
)
app.state.outbox_bootstrap = outbox_bootstrap
owns_outbox_bootstrap = True
acl_policy = getattr(app.state, 'acl_policy', None)
acl_policy = getattr(app.state, "acl_policy", None)
if acl_policy is None and settings is not None:
acl_policy = load_acl_config_from_file(settings.config_path)
app.state.acl_policy = acl_policy
if runtime is None and acl_policy is not None:
if runtime is None and acl_policy is not None and start_runtime:
if settings is None:
settings = load_settings()
app.state.settings = settings
@ -75,7 +77,6 @@ async def _lifespan(app: FastAPI) -> AsyncIterator[None]:
await outbox_bootstrap.dispose()
def create_app(
*,
settings: Settings | None = None,
@ -101,4 +102,4 @@ def create_app(
app = create_app()
__all__ = ['app', 'create_app']
__all__ = ["app", "create_app"]

View File

@ -31,8 +31,15 @@ from app.storage.repositories import (
SourceRegistryRecord,
schema,
)
from app.storage.scan_snapshots import WifiScanSnapshotRecord, WifiScanSnapshotRepository
from app.workers import CachedEventRetentionWorker, CachedExportWorker, SourceHealthWorker
from app.storage.scan_snapshots import (
WifiScanSnapshotRecord,
WifiScanSnapshotRepository,
)
from app.workers import (
CachedEventRetentionWorker,
CachedExportWorker,
SourceHealthWorker,
)
logger = logging.getLogger(__name__)
@ -83,42 +90,37 @@ class _SessionBackedWifiScanSnapshotRepository:
await session.commit()
def _parse_timestamp(value: str) -> datetime:
return datetime.fromisoformat(value.replace('Z', '+00:00')).astimezone(
timezone.utc
)
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
def _source_record_from_row(row: Mapping[str, Any]) -> SourceRegistryRecord | None:
try:
metadata = json.loads(row['metadata_json'] or '{}')
metadata = json.loads(row["metadata_json"] or "{}")
if not isinstance(metadata, dict):
metadata = {'value': metadata}
metadata = {"value": metadata}
return SourceRegistryRecord(
id=row['id'],
source_key=row['source_key'],
source_kind=row['source_kind'],
display_name=row['display_name'],
is_enabled=bool(row['is_enabled']),
id=row["id"],
source_key=row["source_key"],
source_kind=row["source_kind"],
display_name=row["display_name"],
is_enabled=bool(row["is_enabled"]),
metadata=metadata,
created_at=_parse_timestamp(str(row['created_at'])),
updated_at=_parse_timestamp(str(row['updated_at'])),
created_at=_parse_timestamp(str(row["created_at"])),
updated_at=_parse_timestamp(str(row["updated_at"])),
)
except Exception as exc:
logger.warning(
'source registry record skipped',
"source registry record skipped",
extra=build_log_context(
source_key=str(row.get('source_key', '')),
source_kind=str(row.get('source_kind', '')),
source_key=str(row.get("source_key", "")),
source_kind=str(row.get("source_kind", "")),
error=str(exc),
),
)
return None
def _metadata_text(
record: SourceRegistryRecord, key: str, default: str | None
) -> str | None:
@ -130,7 +132,6 @@ def _metadata_text(
return default
def _metadata_int(record: SourceRegistryRecord, key: str, default: int) -> int:
value = record.metadata.get(key)
if value is None:
@ -144,7 +145,6 @@ def _metadata_int(record: SourceRegistryRecord, key: str, default: int) -> int:
return normalized
def _metadata_mapping(
record: SourceRegistryRecord, key: str
) -> Mapping[str, Any] | None:
@ -152,15 +152,13 @@ def _metadata_mapping(
return value if isinstance(value, Mapping) else None
def _source_kind_has_cache_rules(
acl_policy: SourceAclConfig | None, source_kind: str
) -> bool:
if acl_policy is None:
return False
rules = getattr(acl_policy, source_kind, ())
return any(rule.cache_policy == 'cache' for rule in rules)
return any(rule.cache_policy == "cache" for rule in rules)
def _build_journal_adapter(
@ -180,23 +178,20 @@ def _build_journal_adapter(
),
dispatcher=dispatcher,
filter_template=JournalFilter(
source_names=_metadata_mapping(record, 'source_names'),
process_names=_metadata_mapping(record, 'process_names'),
field_matches=_metadata_mapping(record, 'field_matches'),
source_names=_metadata_mapping(record, "source_names"),
process_names=_metadata_mapping(record, "process_names"),
field_matches=_metadata_mapping(record, "field_matches"),
),
clock=clock,
acl_policy=acl_policy,
cache_repository=_SessionBackedCachedEventRepository(
bootstrap.session_factory
),
cache_repository=_SessionBackedCachedEventRepository(bootstrap.session_factory),
cache_ttl_seconds=_metadata_int(
record, 'cache_ttl_seconds', settings.cache_ttl_seconds
record, "cache_ttl_seconds", settings.cache_ttl_seconds
),
history_ttl_seconds=settings.history_ttl_seconds,
)
def _build_dbus_adapter(
record: SourceRegistryRecord,
bootstrap: DatabaseBootstrap,
@ -206,10 +201,10 @@ def _build_dbus_adapter(
clock: Clock,
) -> SourceAdapterProtocol:
wifi_interface_name = _metadata_text(
record, 'wifi_interface_name', settings.wifi_interface_name
record, "wifi_interface_name", settings.wifi_interface_name
)
if wifi_interface_name is None:
raise ValueError('wifi_interface_name must be configured for dbus sources')
raise ValueError("wifi_interface_name must be configured for dbus sources")
return DbusWpaAdapter(
source_key=record.source_key,
source_id=record.id,
@ -217,23 +212,21 @@ def _build_dbus_adapter(
dispatcher=dispatcher,
wifi_interface_name=wifi_interface_name,
acl_policy=acl_policy,
cache_repository=_SessionBackedCachedEventRepository(
bootstrap.session_factory
),
cache_repository=_SessionBackedCachedEventRepository(bootstrap.session_factory),
scan_snapshot_repository=_SessionBackedWifiScanSnapshotRepository(
bootstrap.session_factory
),
clock=clock,
cache_ttl_seconds=_metadata_int(
record, 'cache_ttl_seconds', settings.cache_ttl_seconds
record, "cache_ttl_seconds", settings.cache_ttl_seconds
),
history_ttl_seconds=settings.history_ttl_seconds,
)
DEFAULT_SOURCE_ADAPTER_FACTORIES: dict[str, SourceAdapterFactory] = {
'journal': _build_journal_adapter,
'dbus': _build_dbus_adapter,
"journal": _build_journal_adapter,
"dbus": _build_dbus_adapter,
}
@ -308,7 +301,7 @@ class DaemonRuntime:
self.acl_policy, record.source_kind
):
logger.info(
'source skipped because acl has no cache rules',
"source skipped because acl has no cache rules",
extra=build_log_context(
source_key=record.source_key,
source_kind=record.source_kind,
@ -318,7 +311,7 @@ class DaemonRuntime:
factory = self.source_adapter_factories.get(record.source_kind)
if factory is None:
logger.warning(
'source skipped because no runtime adapter factory exists',
"source skipped because no runtime adapter factory exists",
extra=build_log_context(
source_key=record.source_key,
source_kind=record.source_kind,
@ -346,7 +339,7 @@ class DaemonRuntime:
self._export_tasks.append(asyncio.create_task(worker.run()))
self._started = True
logger.info(
'daemon runtime started',
"daemon runtime started",
extra=build_log_context(
source_count=len(self.source_manager.statuses),
started_count=len(result.started),
@ -358,7 +351,11 @@ class DaemonRuntime:
return result.started
async def stop(self) -> None:
if not self._started and self._retention_task is None and not self._export_tasks:
if (
not self._started
and self._retention_task is None
and not self._export_tasks
):
return
await self.source_manager.stop_all()
@ -378,8 +375,7 @@ class DaemonRuntime:
if self.source_manager.statuses:
await self.health_worker.run_once()
self._started = False
logger.info('daemon runtime stopped')
logger.info("daemon runtime stopped")
def create_daemon_runtime(
@ -397,16 +393,16 @@ def create_daemon_runtime(
outbox_bootstrap=outbox_bootstrap,
acl_policy=acl_policy,
clock=SystemClock() if clock is None else clock,
source_adapter_factories={}
if source_adapter_factories is None
else dict(source_adapter_factories),
source_adapter_factories=(
{} if source_adapter_factories is None else dict(source_adapter_factories)
),
)
__all__ = [
'DaemonRuntime',
'DEFAULT_SOURCE_ADAPTER_FACTORIES',
'SourceAdapterFactory',
'_source_kind_has_cache_rules',
'create_daemon_runtime',
]
"DaemonRuntime",
"DEFAULT_SOURCE_ADAPTER_FACTORIES",
"SourceAdapterFactory",
"_source_kind_has_cache_rules",
"create_daemon_runtime",
]

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +1 @@
from __future__ import annotations

View File

@ -1,4 +1,3 @@
from __future__ import annotations
from collections.abc import Mapping
@ -41,31 +40,31 @@ class AclRule:
def __post_init__(self) -> None:
object.__setattr__(
self, 'selector_name', _strip(self.selector_name, 'selector_name')
self, "selector_name", _strip(self.selector_name, "selector_name")
)
object.__setattr__(
self, 'message_regex', _strip(self.message_regex, 'message_regex')
self, "message_regex", _strip(self.message_regex, "message_regex")
)
cache_policy = _strip(self.cache_policy, 'cache_policy').casefold()
if cache_policy not in {'cache', 'drop'}:
cache_policy = _strip(self.cache_policy, "cache_policy").casefold()
if cache_policy not in {"cache", "drop"}:
raise AclRuleParseError("cache_policy must be either 'cache' or 'drop'")
object.__setattr__(self, 'cache_policy', cache_policy)
object.__setattr__(self, "cache_policy", cache_policy)
if self.send_policy is not None:
object.__setattr__(
self, 'send_policy', _strip(self.send_policy, 'send_policy')
self, "send_policy", _strip(self.send_policy, "send_policy")
)
if self.scope is not None:
object.__setattr__(self, 'scope', _strip(self.scope, 'scope'))
transport_name = _strip(self.transport_name, 'transport_name')
object.__setattr__(self, 'transport_name', transport_name)
object.__setattr__(self, "scope", _strip(self.scope, "scope"))
transport_name = _strip(self.transport_name, "transport_name")
object.__setattr__(self, "transport_name", transport_name)
try:
object.__setattr__(self, '_pattern', re.compile(self.message_regex))
object.__setattr__(self, "_pattern", re.compile(self.message_regex))
except re.error as exc:
raise AclRuleParseError(
'message_regex must be a valid regular expression'
"message_regex must be a valid regular expression"
) from exc
def matches(self, selector_name: str, subject: str) -> bool:
@ -73,19 +72,19 @@ class AclRule:
if not selector:
return False
selector_matches = (
self.selector_name == '*'
self.selector_name == "*"
or self.selector_name.casefold() == selector.casefold()
)
return selector_matches and self._pattern.search(subject) is not None
def to_dict(self) -> dict[str, Any]:
return {
'selector_name': self.selector_name,
'message_regex': self.message_regex,
'cache': self.cache_policy,
'send': self.send_policy,
'scope': self.scope,
'transport': self.transport_name,
"selector_name": self.selector_name,
"message_regex": self.message_regex,
"cache": self.cache_policy,
"send": self.send_policy,
"scope": self.scope,
"transport": self.transport_name,
}
@ -101,13 +100,13 @@ class AclDecision:
def to_dict(self) -> dict[str, Any]:
return {
'allowed': self.allowed,
'source_kind': self.source_kind,
'selector_name': self.selector_name,
'subject': self.subject,
'reason': self.reason,
'transport_name': self.transport_name,
'rule': None if self.rule is None else self.rule.to_dict(),
"allowed": self.allowed,
"source_kind": self.source_kind,
"selector_name": self.selector_name,
"subject": self.subject,
"reason": self.reason,
"transport_name": self.transport_name,
"rule": None if self.rule is None else self.rule.to_dict(),
}
@ -119,12 +118,12 @@ class SourceAclConfig:
def decision_for_journal(
self, *, process_name: str | None, message: str | None
) -> AclDecision:
return self._decision('journal', self.journal, process_name, message)
return self._decision("journal", self.journal, process_name, message)
def decision_for_dbus(
self, *, source_name: str | None, event_name: str | None
) -> AclDecision:
return self._decision('dbus', self.dbus, source_name, event_name)
return self._decision("dbus", self.dbus, source_name, event_name)
def _decision(
self,
@ -141,7 +140,7 @@ class SourceAclConfig:
source_kind=source_kind,
selector_name=selector,
subject=normalized_subject,
reason='missing selector or subject',
reason="missing selector or subject",
)
if not rules:
return AclDecision(
@ -149,17 +148,17 @@ class SourceAclConfig:
source_kind=source_kind,
selector_name=selector,
subject=normalized_subject,
reason=f'no {source_kind} acl rules configured',
reason=f"no {source_kind} acl rules configured",
)
for rule in rules:
if rule.matches(selector, normalized_subject):
return AclDecision(
allowed=rule.cache_policy == 'cache',
allowed=rule.cache_policy == "cache",
source_kind=source_kind,
selector_name=selector,
subject=normalized_subject,
rule=rule,
reason=f'matched {source_kind} acl rule',
reason=f"matched {source_kind} acl rule",
transport_name=rule.transport_name,
)
return AclDecision(
@ -167,27 +166,27 @@ class SourceAclConfig:
source_kind=source_kind,
selector_name=selector,
subject=normalized_subject,
reason=f'no {source_kind} acl rule matched',
reason=f"no {source_kind} acl rule matched",
)
def _parse_acl_rule(raw_rule: Any, index: int, source_kind: str) -> AclRule:
if not isinstance(raw_rule, str) or not raw_rule.strip():
raise AclRuleParseError(
f'acl.{source_kind}[{index}] must be a non-empty string'
f"acl.{source_kind}[{index}] must be a non-empty string"
)
try:
tokens = shlex.split(raw_rule.strip())
except ValueError as exc:
raise AclRuleParseError(
f'acl.{source_kind}[{index}] is invalid: {exc}'
f"acl.{source_kind}[{index}] is invalid: {exc}"
) from exc
if not tokens:
raise AclRuleParseError(f'acl.{source_kind}[{index}] must not be empty')
raise AclRuleParseError(f"acl.{source_kind}[{index}] must not be empty")
cache_policy = tokens[0].strip().casefold()
if cache_policy not in {'cache', 'drop'}:
if cache_policy not in {"cache", "drop"}:
raise AclRuleParseError(
f"acl.{source_kind}[{index}] must start with 'cache' or 'drop'"
)
@ -202,54 +201,54 @@ def _parse_acl_rule(raw_rule: Any, index: int, source_kind: str) -> AclRule:
while position < len(tokens):
token = tokens[position].strip().casefold()
position += 1
if token in {'process', 'process_name'}:
if token in {"process", "process_name"}:
if position >= len(tokens):
raise AclRuleParseError(
f'acl.{source_kind}[{index}].process is missing a value'
f"acl.{source_kind}[{index}].process is missing a value"
)
if selector_name is not None:
raise AclRuleParseError(
f'acl.{source_kind}[{index}] contains duplicate process field'
f"acl.{source_kind}[{index}] contains duplicate process field"
)
selector_name = tokens[position]
elif token in {'regexp', 'message_regex'}:
elif token in {"regexp", "message_regex"}:
if position >= len(tokens):
raise AclRuleParseError(
f'acl.{source_kind}[{index}].regexp is missing a value'
f"acl.{source_kind}[{index}].regexp is missing a value"
)
if message_regex is not None:
raise AclRuleParseError(
f'acl.{source_kind}[{index}] contains duplicate regexp field'
f"acl.{source_kind}[{index}] contains duplicate regexp field"
)
message_regex = tokens[position]
elif token == 'send':
elif token == "send":
if position >= len(tokens):
raise AclRuleParseError(
f'acl.{source_kind}[{index}].send is missing a value'
f"acl.{source_kind}[{index}].send is missing a value"
)
if send_policy is not None:
raise AclRuleParseError(
f'acl.{source_kind}[{index}] contains duplicate send field'
f"acl.{source_kind}[{index}] contains duplicate send field"
)
send_policy = tokens[position]
elif token == 'scope':
elif token == "scope":
if position >= len(tokens):
raise AclRuleParseError(
f'acl.{source_kind}[{index}].scope is missing a value'
f"acl.{source_kind}[{index}].scope is missing a value"
)
if scope is not None:
raise AclRuleParseError(
f'acl.{source_kind}[{index}] contains duplicate scope field'
f"acl.{source_kind}[{index}] contains duplicate scope field"
)
scope = tokens[position]
elif token == 'transport':
elif token == "transport":
if position >= len(tokens):
raise AclRuleParseError(
f'acl.{source_kind}[{index}].transport is missing a value'
f"acl.{source_kind}[{index}].transport is missing a value"
)
if transport_name is not None:
raise AclRuleParseError(
f'acl.{source_kind}[{index}] contains duplicate transport field'
f"acl.{source_kind}[{index}] contains duplicate transport field"
)
transport_name = tokens[position]
else:
@ -259,9 +258,9 @@ def _parse_acl_rule(raw_rule: Any, index: int, source_kind: str) -> AclRule:
position += 1
if selector_name is None:
raise AclRuleParseError(f'acl.{source_kind}[{index}].process is required')
raise AclRuleParseError(f"acl.{source_kind}[{index}].process is required")
if message_regex is None:
raise AclRuleParseError(f'acl.{source_kind}[{index}].regexp is required')
raise AclRuleParseError(f"acl.{source_kind}[{index}].regexp is required")
return AclRule(
selector_name=selector_name,
@ -277,7 +276,7 @@ def _parse_acl_rules(raw_rules: Any, source_kind: str) -> tuple[AclRule, ...]:
if raw_rules is None:
return ()
if not isinstance(raw_rules, list):
raise AclConfigError(f'acl.{source_kind} must be a list of ACL rule strings')
raise AclConfigError(f"acl.{source_kind} must be a list of ACL rule strings")
return tuple(
_parse_acl_rule(raw_rule, index, source_kind)
for index, raw_rule in enumerate(raw_rules)
@ -285,35 +284,35 @@ def _parse_acl_rules(raw_rules: Any, source_kind: str) -> tuple[AclRule, ...]:
def load_acl_config_from_mapping(raw: Mapping[str, Any]) -> SourceAclConfig:
acl_section = raw.get('acl')
acl_section = raw.get("acl")
if acl_section is None:
return SourceAclConfig()
if not isinstance(acl_section, Mapping):
raise AclConfigError('acl section must be a mapping')
raise AclConfigError("acl section must be a mapping")
return SourceAclConfig(
journal=_parse_acl_rules(acl_section.get('journal'), 'journal'),
dbus=_parse_acl_rules(acl_section.get('dbus'), 'dbus'),
journal=_parse_acl_rules(acl_section.get("journal"), "journal"),
dbus=_parse_acl_rules(acl_section.get("dbus"), "dbus"),
)
def load_acl_config_from_file(path: str | Path) -> SourceAclConfig:
config_path = Path(path)
try:
with config_path.open('rb') as handle:
with config_path.open("rb") as handle:
raw = tomllib.load(handle)
except FileNotFoundError as exc:
raise AclConfigError(f'ACL config file not found: {config_path}') from exc
raise AclConfigError(f"ACL config file not found: {config_path}") from exc
if not isinstance(raw, Mapping):
raise AclConfigError('ACL config file must contain a mapping')
raise AclConfigError("ACL config file must contain a mapping")
return load_acl_config_from_mapping(raw)
__all__ = [
'AclConfigError',
'AclDecision',
'AclRule',
'AclRuleParseError',
'SourceAclConfig',
'load_acl_config_from_file',
'load_acl_config_from_mapping',
"AclConfigError",
"AclDecision",
"AclRule",
"AclRuleParseError",
"SourceAclConfig",
"load_acl_config_from_file",
"load_acl_config_from_mapping",
]

View File

@ -13,9 +13,9 @@ def resolve_sqlalchemy_url(
*,
config_path: Path | None = None,
) -> str:
configured_url = (alembic_config.get_main_option('sqlalchemy.url') or '').strip()
configured_url = (alembic_config.get_main_option("sqlalchemy.url") or "").strip()
if configured_url and configured_url != DEFAULT_ALEMBIC_SQLALCHEMY_URL:
return configured_url
settings = load_settings(config_path=config_path)
return settings.database_dsn
return settings.database_dsn

View File

@ -22,4 +22,4 @@ DEFAULT_ALEMBIC_SQLALCHEMY_URL = "sqlite+aiosqlite:///wf_agent.sqlite3"
DEFAULT_OUTBOX_DATABASE_DSN = "sqlite+aiosqlite:///wf_agent_outbox.sqlite3"
ALLOWED_DATABASE_SCHEMES = ("sqlite+aiosqlite",)
TEST_DATABASE_NAME_MARKERS = ("test", "tests", "pytest")
TEST_DATABASE_NAME_MARKERS = ("test", "tests", "pytest")

View File

@ -19,9 +19,9 @@ class CachedMessagePacketBuilder:
messages: tuple[CachedEventRecord, ...],
) -> dict[str, object]:
return {
'packet_id': str(UUID(str(packet_id))),
'transport_name': transport_name,
'created_at': utc_text(created_at),
'message_count': len(messages),
'messages': [message.to_dict() for message in messages],
}
"packet_id": str(UUID(str(packet_id))),
"transport_name": transport_name,
"created_at": utc_text(created_at),
"message_count": len(messages),
"messages": [message.to_dict() for message in messages],
}

View File

@ -36,13 +36,15 @@ class FakeNorthboundClient:
@dataclass(frozen=True, slots=True)
class WebhookTransportClient:
url: str
headers: MappingProxyType[str, str] = field(default_factory=lambda: MappingProxyType({}))
headers: MappingProxyType[str, str] = field(
default_factory=lambda: MappingProxyType({})
)
timeout_seconds: float = 30.0
def __post_init__(self) -> None:
object.__setattr__(self, 'url', self.url.strip())
object.__setattr__(self, 'headers', MappingProxyType(dict(self.headers)))
object.__setattr__(self, 'timeout_seconds', float(self.timeout_seconds))
object.__setattr__(self, "url", self.url.strip())
object.__setattr__(self, "headers", MappingProxyType(dict(self.headers)))
object.__setattr__(self, "timeout_seconds", float(self.timeout_seconds))
async def send(self, payload: dict[str, Any]) -> Any:
async with httpx.AsyncClient(timeout=self.timeout_seconds) as client:
@ -123,4 +125,4 @@ __all__ = [
"NorthboundClientProtocol",
"NorthboundDeliveryMessage",
"WebhookTransportClient",
]
]

View File

@ -1,4 +1,3 @@
from __future__ import annotations
from typing import Any, Mapping, Protocol, runtime_checkable
@ -144,30 +143,30 @@ class OutboxRecordLike(
__all__ = [
'CanonicalEntityKind',
'CommandId',
'CommandRecordLike',
'CommandStatus',
'CorrelationContext',
'CorrelationId',
'DeliveryMode',
'EventLogEntryLike',
'LocationSnapshotLike',
'OutboxRecordLike',
'OutboxStatus',
'Priority',
'RecordLifecycleStatus',
'SourceId',
'SourceStatus',
'StateSnapshotLike',
'SupportsCanonicalIdentity',
'SupportsCommandStatus',
'SupportsLifecycleStatus',
'SupportsOutboxStatus',
'SupportsPayload',
'SupportsSourceContext',
'SupportsSourceStatus',
'SupportsToDict',
'SupportsTransportName',
'UtcTimestamp',
"CanonicalEntityKind",
"CommandId",
"CommandRecordLike",
"CommandStatus",
"CorrelationContext",
"CorrelationId",
"DeliveryMode",
"EventLogEntryLike",
"LocationSnapshotLike",
"OutboxRecordLike",
"OutboxStatus",
"Priority",
"RecordLifecycleStatus",
"SourceId",
"SourceStatus",
"StateSnapshotLike",
"SupportsCanonicalIdentity",
"SupportsCommandStatus",
"SupportsLifecycleStatus",
"SupportsOutboxStatus",
"SupportsPayload",
"SupportsSourceContext",
"SupportsSourceStatus",
"SupportsToDict",
"SupportsTransportName",
"UtcTimestamp",
]

View File

@ -411,9 +411,9 @@ class OutboxRecord:
"transport_name": self.transport_name,
"payload": _serialize_value(self.payload),
"attempt_count": self.attempt_count,
"last_attempt_at": None
if self.last_attempt_at is None
else str(self.last_attempt_at),
"last_attempt_at": (
None if self.last_attempt_at is None else str(self.last_attempt_at)
),
"last_error": self.last_error,
"correlation": self.correlation.as_dict(),
}

View File

@ -1,4 +1,3 @@
from __future__ import annotations
from dataclasses import dataclass, field
@ -21,5 +20,5 @@ class IngestionEnvelope:
return
transport_name = self.transport_name.strip()
if not transport_name:
raise ValueError('transport_name must not be empty')
object.__setattr__(self, 'transport_name', transport_name)
raise ValueError("transport_name must not be empty")
object.__setattr__(self, "transport_name", transport_name)

View File

@ -129,9 +129,11 @@ class SourceManager:
adapter=adapter,
registered_at=UtcTimestamp.from_value(self.clock.now()),
enabled=bool(adapter.enabled),
lifecycle_state=SourceLifecycleState.DISABLED
if not adapter.enabled
else SourceLifecycleState.REGISTERED,
lifecycle_state=(
SourceLifecycleState.DISABLED
if not adapter.enabled
else SourceLifecycleState.REGISTERED
),
)
adapter.set_health_reporter(self._build_health_reporter(source_key))
self._entries[source_key] = entry

View File

@ -122,9 +122,11 @@ class SourceDeliveryClassifier:
)
priority = self._merge_priority(
record.priority,
Priority.CRITICAL
if self._command_is_failure(record.status, record.result)
else Priority.HIGH,
(
Priority.CRITICAL
if self._command_is_failure(record.status, record.result)
else Priority.HIGH
),
)
return replace(record, delivery_mode=delivery_mode, priority=priority)
if record.status in {

View File

@ -5,7 +5,6 @@ from typing import TypeAlias
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.constants import DEFAULT_OUTBOX_TRANSPORT_NAME
from app.core.constants import DEFAULT_OUTBOX_TRANSPORT_NAME
from app.core.ids import uuid4_id
from app.domain import (

View File

@ -1,49 +1,62 @@
from __future__ import annotations
from sqlalchemy import Column, ForeignKey, Integer, MetaData, String, Table, Text, UniqueConstraint
from sqlalchemy import (
Column,
ForeignKey,
Integer,
MetaData,
String,
Table,
Text,
UniqueConstraint,
)
from app.storage.db import DatabaseBootstrap, create_database_bootstrap
outbox_metadata = MetaData()
outbox_packets = Table(
'outbox_packets',
"outbox_packets",
outbox_metadata,
Column('packet_id', String(36), primary_key=True),
Column('transport_name', String(128), nullable=False),
Column('status', String(32), nullable=False),
Column('message_count', Integer(), nullable=False),
Column('payload_json', Text(), nullable=False),
Column('created_at', String(40), nullable=False),
Column('locked_at', String(40)),
Column("packet_id", String(36), primary_key=True),
Column("transport_name", String(128), nullable=False),
Column("status", String(32), nullable=False),
Column("message_count", Integer(), nullable=False),
Column("payload_json", Text(), nullable=False),
Column("created_at", String(40), nullable=False),
Column("locked_at", String(40)),
)
outbox_packet_items = Table(
'outbox_packet_items',
"outbox_packet_items",
outbox_metadata,
Column(
'packet_id',
"packet_id",
String(36),
ForeignKey('outbox_packets.packet_id', ondelete='CASCADE'),
ForeignKey("outbox_packets.packet_id", ondelete="CASCADE"),
nullable=False,
),
Column('cached_event_id', String(36), nullable=False),
UniqueConstraint('packet_id', 'cached_event_id', name='uq_outbox_packet_item'),
Column("cached_event_id", String(36), nullable=False),
UniqueConstraint("packet_id", "cached_event_id", name="uq_outbox_packet_item"),
)
outbox_counters = Table(
'outbox_counters',
"outbox_counters",
outbox_metadata,
Column('transport_name', String(128), nullable=False),
Column('outcome', String(64), nullable=False),
Column('packet_count', Integer(), nullable=False),
Column('message_count', Integer(), nullable=False),
Column('updated_at', String(40), nullable=False),
UniqueConstraint('transport_name', 'outcome', name='uq_outbox_counter_transport_outcome'),
Column("transport_name", String(128), nullable=False),
Column("outcome", String(64), nullable=False),
Column("packet_count", Integer(), nullable=False),
Column("message_count", Integer(), nullable=False),
Column("updated_at", String(40), nullable=False),
UniqueConstraint(
"transport_name", "outcome", name="uq_outbox_counter_transport_outcome"
),
)
def create_outbox_database_bootstrap(database_dsn: str, *, echo: bool = False) -> DatabaseBootstrap:
def create_outbox_database_bootstrap(
database_dsn: str, *, echo: bool = False
) -> DatabaseBootstrap:
return create_database_bootstrap(database_dsn, echo=echo)
@ -53,10 +66,10 @@ async def initialize_outbox_database(bootstrap: DatabaseBootstrap) -> None:
__all__ = [
'create_outbox_database_bootstrap',
'initialize_outbox_database',
'outbox_counters',
'outbox_metadata',
'outbox_packet_items',
'outbox_packets',
]
"create_outbox_database_bootstrap",
"initialize_outbox_database",
"outbox_counters",
"outbox_metadata",
"outbox_packet_items",
"outbox_packets",
]

View File

@ -1,6 +1,9 @@
from __future__ import annotations
from app.storage.scan_snapshots import WifiScanSnapshotRecord, WifiScanSnapshotRepository
from app.storage.scan_snapshots import (
WifiScanSnapshotRecord,
WifiScanSnapshotRepository,
)
from .export_records import (
CachedEventDeliveryRecord,
OutboxCounterRecord,
@ -56,4 +59,4 @@ __all__ = [
"WifiEventRepository",
"WifiScanSnapshotRecord",
"WifiScanSnapshotRepository",
]
]

View File

@ -65,15 +65,21 @@ def correlation_context_from_dict(
source_id = value.get("source_id")
command_id = value.get("command_id")
return CorrelationContext(
correlation_id=CorrelationId.from_value(correlation_id)
if isinstance(correlation_id, str) and correlation_id
else None,
source_id=SourceId.from_value(source_id)
if isinstance(source_id, str) and source_id
else None,
command_id=CommandId.from_value(command_id)
if isinstance(command_id, str) and command_id
else None,
correlation_id=(
CorrelationId.from_value(correlation_id)
if isinstance(correlation_id, str) and correlation_id
else None
),
source_id=(
SourceId.from_value(source_id)
if isinstance(source_id, str) and source_id
else None
),
command_id=(
CommandId.from_value(command_id)
if isinstance(command_id, str) and command_id
else None
),
)

View File

@ -22,27 +22,27 @@ class CachedEventDeliveryRecord:
last_error: str | None = None
def __post_init__(self) -> None:
object.__setattr__(self, 'cached_event_id', parse_uuid(self.cached_event_id))
object.__setattr__(self, 'transport_name', self.transport_name.strip())
object.__setattr__(self, "cached_event_id", parse_uuid(self.cached_event_id))
object.__setattr__(self, "transport_name", self.transport_name.strip())
object.__setattr__(
self,
'delivery_status',
"delivery_status",
CachedEventDeliveryStatus.from_value(self.delivery_status),
)
if not isinstance(self.next_export_at, UtcTimestamp):
object.__setattr__(
self,
'next_export_at',
"next_export_at",
UtcTimestamp.from_value(self.next_export_at),
)
if self.packet_id is not None:
object.__setattr__(self, 'packet_id', parse_uuid(self.packet_id))
for field_name in ('prepared_at', 'delivered_at', 'undelivered_at'):
object.__setattr__(self, "packet_id", parse_uuid(self.packet_id))
for field_name in ("prepared_at", "delivered_at", "undelivered_at"):
value = getattr(self, field_name)
if value is not None and not isinstance(value, UtcTimestamp):
object.__setattr__(self, field_name, UtcTimestamp.from_value(value))
if self.last_error is not None:
object.__setattr__(self, 'last_error', self.last_error.strip() or None)
object.__setattr__(self, "last_error", self.last_error.strip() or None)
@dataclass(frozen=True, slots=True)
@ -56,17 +56,23 @@ class OutboxPacketRecord:
locked_at: UtcTimestamp | datetime | None = None
def __post_init__(self) -> None:
object.__setattr__(self, 'packet_id', parse_uuid(self.packet_id))
object.__setattr__(self, 'transport_name', self.transport_name.strip())
object.__setattr__(self, 'status', TransportPacketStatus.from_value(self.status))
object.__setattr__(self, 'message_count', int(self.message_count))
object.__setattr__(self, "packet_id", parse_uuid(self.packet_id))
object.__setattr__(self, "transport_name", self.transport_name.strip())
object.__setattr__(
self, "status", TransportPacketStatus.from_value(self.status)
)
object.__setattr__(self, "message_count", int(self.message_count))
if self.message_count < 0:
raise ValueError('message_count must not be negative')
raise ValueError("message_count must not be negative")
if not isinstance(self.created_at, UtcTimestamp):
object.__setattr__(self, 'created_at', UtcTimestamp.from_value(self.created_at))
object.__setattr__(
self, "created_at", UtcTimestamp.from_value(self.created_at)
)
if self.locked_at is not None and not isinstance(self.locked_at, UtcTimestamp):
object.__setattr__(self, 'locked_at', UtcTimestamp.from_value(self.locked_at))
object.__setattr__(self, 'payload', dict(self.payload))
object.__setattr__(
self, "locked_at", UtcTimestamp.from_value(self.locked_at)
)
object.__setattr__(self, "payload", dict(self.payload))
@dataclass(frozen=True, slots=True)
@ -75,8 +81,8 @@ class OutboxPacketItemRecord:
cached_event_id: UUID | str
def __post_init__(self) -> None:
object.__setattr__(self, 'packet_id', parse_uuid(self.packet_id))
object.__setattr__(self, 'cached_event_id', parse_uuid(self.cached_event_id))
object.__setattr__(self, "packet_id", parse_uuid(self.packet_id))
object.__setattr__(self, "cached_event_id", parse_uuid(self.cached_event_id))
@dataclass(frozen=True, slots=True)
@ -88,11 +94,13 @@ class OutboxCounterRecord:
updated_at: UtcTimestamp | datetime
def __post_init__(self) -> None:
object.__setattr__(self, 'transport_name', self.transport_name.strip())
object.__setattr__(self, 'outcome', self.outcome.strip().lower())
object.__setattr__(self, 'packet_count', int(self.packet_count))
object.__setattr__(self, 'message_count', int(self.message_count))
object.__setattr__(self, "transport_name", self.transport_name.strip())
object.__setattr__(self, "outcome", self.outcome.strip().lower())
object.__setattr__(self, "packet_count", int(self.packet_count))
object.__setattr__(self, "message_count", int(self.message_count))
if self.packet_count < 0 or self.message_count < 0:
raise ValueError('outbox counters must not be negative')
raise ValueError("outbox counters must not be negative")
if not isinstance(self.updated_at, UtcTimestamp):
object.__setattr__(self, 'updated_at', UtcTimestamp.from_value(self.updated_at))
object.__setattr__(
self, "updated_at", UtcTimestamp.from_value(self.updated_at)
)

View File

@ -1,7 +1,7 @@
from __future__ import annotations
from collections.abc import Iterable, Mapping, Sequence
from datetime import datetime, timedelta, timezone
from datetime import datetime, timedelta
from uuid import UUID
from sqlalchemy import delete, select, update
@ -10,7 +10,13 @@ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from app.domain.enums import CachedEventDeliveryStatus, TransportPacketStatus
from app.storage.outbox_db import outbox_counters, outbox_packet_items, outbox_packets
from app.storage.repositories import schema
from app.storage.repositories.base import RepositoryBase, json_payload, json_text, parse_utc_text, utc_text
from app.storage.repositories.base import (
RepositoryBase,
json_payload,
json_text,
parse_utc_text,
utc_text,
)
from app.storage.repositories.export_records import (
CachedEventDeliveryRecord,
OutboxCounterRecord,
@ -29,7 +35,9 @@ class CachedEventDeliveryRepository(RepositoryBase):
period_seconds_by_transport: Mapping[str, int],
) -> None:
for cached_event in cached_events:
period_seconds = period_seconds_by_transport.get(cached_event.transport_name)
period_seconds = period_seconds_by_transport.get(
cached_event.transport_name
)
if period_seconds is None:
continue
next_export_at = cached_event.created_at.as_datetime() + timedelta(
@ -62,11 +70,14 @@ class CachedEventDeliveryRepository(RepositoryBase):
.select_from(
schema.cached_events.outerjoin(
schema.cached_event_delivery,
schema.cached_events.c.id == schema.cached_event_delivery.c.cached_event_id,
schema.cached_events.c.id
== schema.cached_event_delivery.c.cached_event_id,
)
)
.where(schema.cached_event_delivery.c.cached_event_id.is_(None))
.order_by(schema.cached_events.c.created_at.asc(), schema.cached_events.c.id.asc())
.order_by(
schema.cached_events.c.created_at.asc(), schema.cached_events.c.id.asc()
)
.limit(limit)
)
if transport_name is not None:
@ -85,7 +96,7 @@ class CachedEventDeliveryRepository(RepositoryBase):
)
result = await self.session.execute(stmt)
return {
row['cached_event_id']: _delivery_from_row(dict(row))
row["cached_event_id"]: _delivery_from_row(dict(row))
for row in result.mappings().all()
}
@ -101,15 +112,20 @@ class CachedEventDeliveryRepository(RepositoryBase):
.select_from(
schema.cached_events.join(
schema.cached_event_delivery,
schema.cached_events.c.id == schema.cached_event_delivery.c.cached_event_id,
schema.cached_events.c.id
== schema.cached_event_delivery.c.cached_event_id,
)
)
.where(
schema.cached_event_delivery.c.transport_name == transport_name,
schema.cached_event_delivery.c.delivery_status == CachedEventDeliveryStatus.PENDING.value,
schema.cached_event_delivery.c.delivery_status
== CachedEventDeliveryStatus.PENDING.value,
schema.cached_event_delivery.c.next_export_at <= utc_text(as_of),
)
.order_by(schema.cached_event_delivery.c.next_export_at.asc(), schema.cached_events.c.id.asc())
.order_by(
schema.cached_event_delivery.c.next_export_at.asc(),
schema.cached_events.c.id.asc(),
)
.limit(limit)
)
result = await self.session.execute(stmt)
@ -118,7 +134,8 @@ class CachedEventDeliveryRepository(RepositoryBase):
async def list_prepared_packet_ids(self, *, transport_name: str) -> set[str]:
stmt = select(schema.cached_event_delivery.c.packet_id).where(
schema.cached_event_delivery.c.transport_name == transport_name,
schema.cached_event_delivery.c.delivery_status == CachedEventDeliveryStatus.PREPARED.value,
schema.cached_event_delivery.c.delivery_status
== CachedEventDeliveryStatus.PREPARED.value,
schema.cached_event_delivery.c.packet_id.is_not(None),
)
result = await self.session.execute(stmt)
@ -132,15 +149,20 @@ class CachedEventDeliveryRepository(RepositoryBase):
) -> int:
stmt = update(schema.cached_event_delivery).where(
schema.cached_event_delivery.c.transport_name == transport_name,
schema.cached_event_delivery.c.delivery_status == CachedEventDeliveryStatus.PREPARED.value,
schema.cached_event_delivery.c.delivery_status
== CachedEventDeliveryStatus.PREPARED.value,
)
if existing_packet_ids:
stmt = stmt.where(~schema.cached_event_delivery.c.packet_id.in_(sorted(existing_packet_ids)))
stmt = stmt.where(
~schema.cached_event_delivery.c.packet_id.in_(
sorted(existing_packet_ids)
)
)
payload = {
'delivery_status': CachedEventDeliveryStatus.PENDING.value,
'packet_id': None,
'prepared_at': None,
'last_error': None,
"delivery_status": CachedEventDeliveryStatus.PENDING.value,
"packet_id": None,
"prepared_at": None,
"last_error": None,
}
result = await self.session.execute(stmt.values(**payload))
return int(result.rowcount or 0)
@ -199,7 +221,9 @@ class CachedEventDeliveryRepository(RepositoryBase):
) -> int:
stmt = (
update(schema.cached_event_delivery)
.where(schema.cached_event_delivery.c.packet_id == str(UUID(str(packet_id))))
.where(
schema.cached_event_delivery.c.packet_id == str(UUID(str(packet_id)))
)
.values(
delivery_status=CachedEventDeliveryStatus.DELIVERED.value,
packet_id=None,
@ -220,7 +244,9 @@ class CachedEventDeliveryRepository(RepositoryBase):
) -> int:
stmt = (
update(schema.cached_event_delivery)
.where(schema.cached_event_delivery.c.packet_id == str(UUID(str(packet_id))))
.where(
schema.cached_event_delivery.c.packet_id == str(UUID(str(packet_id)))
)
.values(
delivery_status=CachedEventDeliveryStatus.UNDELIVERED.value,
packet_id=None,
@ -247,7 +273,9 @@ class TransportOutboxRepository(RepositoryBase):
message_count=packet.message_count,
payload_json=json_text(packet.payload),
created_at=utc_text(packet.created_at),
locked_at=utc_text(packet.locked_at) if packet.locked_at is not None else None,
locked_at=(
utc_text(packet.locked_at) if packet.locked_at is not None else None
),
)
)
if cached_event_ids:
@ -255,27 +283,35 @@ class TransportOutboxRepository(RepositoryBase):
sqlite_insert(outbox_packet_items),
[
{
'packet_id': str(packet.packet_id),
'cached_event_id': str(UUID(str(cached_event_id))),
"packet_id": str(packet.packet_id),
"cached_event_id": str(UUID(str(cached_event_id))),
}
for cached_event_id in cached_event_ids
],
)
async def list_packets(self, *, transport_name: str | None = None) -> list[OutboxPacketRecord]:
stmt = select(outbox_packets).order_by(outbox_packets.c.created_at.asc(), outbox_packets.c.packet_id.asc())
async def list_packets(
self, *, transport_name: str | None = None
) -> list[OutboxPacketRecord]:
stmt = select(outbox_packets).order_by(
outbox_packets.c.created_at.asc(), outbox_packets.c.packet_id.asc()
)
if transport_name is not None:
stmt = stmt.where(outbox_packets.c.transport_name == transport_name)
result = await self.session.execute(stmt)
return [_packet_from_row(dict(row)) for row in result.mappings().all()]
async def get_packet(self, packet_id: UUID | str) -> OutboxPacketRecord | None:
stmt = select(outbox_packets).where(outbox_packets.c.packet_id == str(UUID(str(packet_id))))
stmt = select(outbox_packets).where(
outbox_packets.c.packet_id == str(UUID(str(packet_id)))
)
result = await self.session.execute(stmt)
row = result.mappings().first()
return None if row is None else _packet_from_row(dict(row))
async def list_packet_items(self, packet_id: UUID | str) -> list[OutboxPacketItemRecord]:
async def list_packet_items(
self, packet_id: UUID | str
) -> list[OutboxPacketItemRecord]:
stmt = select(outbox_packet_items).where(
outbox_packet_items.c.packet_id == str(UUID(str(packet_id)))
)
@ -298,7 +334,9 @@ class TransportOutboxRepository(RepositoryBase):
async def delete_packet(self, packet_id: UUID | str) -> int:
result = await self.session.execute(
delete(outbox_packets).where(outbox_packets.c.packet_id == str(UUID(str(packet_id))))
delete(outbox_packets).where(
outbox_packets.c.packet_id == str(UUID(str(packet_id)))
)
)
return int(result.rowcount or 0)
@ -324,18 +362,23 @@ class TransportOutboxRepository(RepositoryBase):
updated_at=utc_text(updated_at),
)
stmt = stmt.on_conflict_do_update(
index_elements=[outbox_counters.c.transport_name, outbox_counters.c.outcome],
index_elements=[
outbox_counters.c.transport_name,
outbox_counters.c.outcome,
],
set_={
'packet_count': outbox_counters.c.packet_count + packet_count,
'message_count': outbox_counters.c.message_count + message_count,
'updated_at': utc_text(updated_at),
"packet_count": outbox_counters.c.packet_count + packet_count,
"message_count": outbox_counters.c.message_count + message_count,
"updated_at": utc_text(updated_at),
},
)
await self.session.execute(stmt)
async def list_counters(self) -> list[OutboxCounterRecord]:
result = await self.session.execute(
select(outbox_counters).order_by(outbox_counters.c.transport_name.asc(), outbox_counters.c.outcome.asc())
select(outbox_counters).order_by(
outbox_counters.c.transport_name.asc(), outbox_counters.c.outcome.asc()
)
)
return [_counter_from_row(dict(row)) for row in result.mappings().all()]
@ -344,48 +387,44 @@ class TransportOutboxRepository(RepositoryBase):
return int(result.rowcount or 0)
def _delivery_from_row(row: dict[str, object]) -> CachedEventDeliveryRecord:
return CachedEventDeliveryRecord(
cached_event_id=row['cached_event_id'],
transport_name=str(row['transport_name']),
delivery_status=str(row['delivery_status']),
next_export_at=parse_utc_text(row['next_export_at']), # type: ignore[arg-type]
packet_id=row.get('packet_id'),
prepared_at=parse_utc_text(row.get('prepared_at')), # type: ignore[arg-type]
delivered_at=parse_utc_text(row.get('delivered_at')), # type: ignore[arg-type]
undelivered_at=parse_utc_text(row.get('undelivered_at')), # type: ignore[arg-type]
last_error=None if row.get('last_error') is None else str(row['last_error']),
cached_event_id=row["cached_event_id"],
transport_name=str(row["transport_name"]),
delivery_status=str(row["delivery_status"]),
next_export_at=parse_utc_text(row["next_export_at"]), # type: ignore[arg-type]
packet_id=row.get("packet_id"),
prepared_at=parse_utc_text(row.get("prepared_at")), # type: ignore[arg-type]
delivered_at=parse_utc_text(row.get("delivered_at")), # type: ignore[arg-type]
undelivered_at=parse_utc_text(row.get("undelivered_at")), # type: ignore[arg-type]
last_error=None if row.get("last_error") is None else str(row["last_error"]),
)
def _packet_from_row(row: dict[str, object]) -> OutboxPacketRecord:
return OutboxPacketRecord(
packet_id=row['packet_id'],
transport_name=str(row['transport_name']),
status=str(row['status']),
message_count=int(row['message_count']),
payload=json_payload(str(row['payload_json'])),
created_at=parse_utc_text(row['created_at']), # type: ignore[arg-type]
locked_at=parse_utc_text(row.get('locked_at')), # type: ignore[arg-type]
packet_id=row["packet_id"],
transport_name=str(row["transport_name"]),
status=str(row["status"]),
message_count=int(row["message_count"]),
payload=json_payload(str(row["payload_json"])),
created_at=parse_utc_text(row["created_at"]), # type: ignore[arg-type]
locked_at=parse_utc_text(row.get("locked_at")), # type: ignore[arg-type]
)
def _packet_item_from_row(row: dict[str, object]) -> OutboxPacketItemRecord:
return OutboxPacketItemRecord(
packet_id=row['packet_id'],
cached_event_id=row['cached_event_id'],
packet_id=row["packet_id"],
cached_event_id=row["cached_event_id"],
)
def _counter_from_row(row: dict[str, object]) -> OutboxCounterRecord:
return OutboxCounterRecord(
transport_name=str(row['transport_name']),
outcome=str(row['outcome']),
packet_count=int(row['packet_count']),
message_count=int(row['message_count']),
updated_at=parse_utc_text(row['updated_at']), # type: ignore[arg-type]
)
transport_name=str(row["transport_name"]),
outcome=str(row["outcome"]),
packet_count=int(row["packet_count"]),
message_count=int(row["message_count"]),
updated_at=parse_utc_text(row["updated_at"]), # type: ignore[arg-type]
)

View File

@ -99,12 +99,14 @@ class SourceHealthRecord:
return {
"source_id": source_id_text(self.source_id),
"status": self.status.value,
"last_seen_at": None
if self.last_seen_at is None
else utc_text(self.last_seen_at),
"last_heartbeat_at": None
if self.last_heartbeat_at is None
else utc_text(self.last_heartbeat_at),
"last_seen_at": (
None if self.last_seen_at is None else utc_text(self.last_seen_at)
),
"last_heartbeat_at": (
None
if self.last_heartbeat_at is None
else utc_text(self.last_heartbeat_at)
),
"last_error": self.last_error,
"details": self.details,
"created_at": utc_text(self.created_at),
@ -194,9 +196,7 @@ class CachedEventRecord:
object.__setattr__(self, "source_id", SourceId.from_value(self.source_id))
object.__setattr__(self, "source_key", self.source_key.strip())
object.__setattr__(self, "source_kind", self.source_kind.strip())
object.__setattr__(
self, "ingestion_channel", self.ingestion_channel.strip()
)
object.__setattr__(self, "ingestion_channel", self.ingestion_channel.strip())
object.__setattr__(self, "event_label", self.event_label.strip())
raw_event_name = (
self.raw_event_name.strip() if self.raw_event_name is not None else ""
@ -211,9 +211,7 @@ class CachedEventRecord:
raise ValueError("event_origin must be 'raw' or 'derived'")
object.__setattr__(self, "event_origin", event_origin)
if self.derived_from is not None:
object.__setattr__(
self, "derived_from", self.derived_from.strip() or None
)
object.__setattr__(self, "derived_from", self.derived_from.strip() or None)
if not isinstance(self.created_at, UtcTimestamp):
object.__setattr__(
self, "created_at", UtcTimestamp.from_value(self.created_at)

View File

@ -158,9 +158,9 @@ def _command_values(command: CommandRecord) -> dict[str, Any]:
"delivery_mode": payload["delivery_mode"],
"priority": payload["priority"],
"arguments_json": json_text(payload["arguments"]),
"result_json": None
if payload["result"] is None
else json_text(payload["result"]),
"result_json": (
None if payload["result"] is None else json_text(payload["result"])
),
"correlation_json": json_text(payload["correlation"]),
}
@ -680,7 +680,9 @@ class CachedEventRepository(RepositoryBase):
async def purge_older_than(self, cutoff: datetime | UtcTimestamp) -> int:
cutoff_text = utc_text(cutoff)
result = await self.session.execute(
delete(schema.cached_events).where(schema.cached_events.c.created_at <= cutoff_text)
delete(schema.cached_events).where(
schema.cached_events.c.created_at <= cutoff_text
)
)
return int(result.rowcount or 0)
@ -694,19 +696,17 @@ class CachedEventRepository(RepositoryBase):
if source_key is not None:
source_text = source_key.strip()
if not source_text:
raise ValueError('source_key must not be empty')
raise ValueError("source_key must not be empty")
stmt = stmt.where(schema.cached_events.c.source_key == source_text)
if scope is not None:
scope_text = scope.strip()
if not scope_text:
raise ValueError('scope must not be empty')
raise ValueError("scope must not be empty")
stmt = stmt.where(schema.cached_events.c.mark == scope_text)
result = await self.session.execute(stmt)
return int(result.rowcount or 0)
class CommandRepository(RepositoryBase):
async def save(self, command: CommandRecord) -> None:
stmt = sqlite_insert(schema.commands).values(_command_values(command))
@ -869,7 +869,7 @@ class OutboxRepository(RepositoryBase):
if transport_name is not None:
transport_text = transport_name.strip()
if not transport_text:
raise ValueError('transport_name must not be empty')
raise ValueError("transport_name must not be empty")
stmt = stmt.where(schema.outbox.c.transport_name == transport_text)
result = await self.session.execute(stmt)
return [self._row_to_record(dict(row)) for row in result.mappings().all()]

View File

@ -145,7 +145,9 @@ outbox = Table(
metadata,
Column("id", String(36), primary_key=True),
Column("source_id", String(36), ForeignKey("source_registry.id")),
Column("transport_name", String(128), nullable=False, server_default=text("'default'")),
Column(
"transport_name", String(128), nullable=False, server_default=text("'default'")
),
Column("related_entity_kind", String(32), nullable=False),
Column("related_entity_id", String(36), nullable=False),
Column("status", String(32), nullable=False),
@ -169,7 +171,9 @@ cached_events = Table(
Column("source_kind", String(64), nullable=False),
Column("ingestion_channel", String(32), nullable=False),
Column("event_label", String(128), nullable=False),
Column("transport_name", String(128), nullable=False, server_default=text("'default'")),
Column(
"transport_name", String(128), nullable=False, server_default=text("'default'")
),
Column("raw_event_name", String(128)),
Column("event_origin", String(16)),
Column("derived_from", String(128)),

View File

@ -10,7 +10,14 @@ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from app.domain.value_objects import SourceId, UtcTimestamp
from app.storage.repositories.base import RepositoryBase, json_text, json_value, parse_utc_text, source_id_text, utc_text
from app.storage.repositories.base import (
RepositoryBase,
json_text,
json_value,
parse_utc_text,
source_id_text,
utc_text,
)
from app.storage.repositories.schema import wifi_scan_snapshots
@ -21,8 +28,12 @@ class WifiScanSnapshotRecord:
interface_name: str
refreshed_at: UtcTimestamp | datetime
results: list[dict[str, Any]] = field(default_factory=list)
created_at: UtcTimestamp | datetime = field(default_factory=lambda: UtcTimestamp.from_value(datetime.now(timezone.utc)))
updated_at: UtcTimestamp | datetime = field(default_factory=lambda: UtcTimestamp.from_value(datetime.now(timezone.utc)))
created_at: UtcTimestamp | datetime = field(
default_factory=lambda: UtcTimestamp.from_value(datetime.now(timezone.utc))
)
updated_at: UtcTimestamp | datetime = field(
default_factory=lambda: UtcTimestamp.from_value(datetime.now(timezone.utc))
)
def __post_init__(self) -> None:
object.__setattr__(self, "source_id", SourceId.from_value(self.source_id))

View File

@ -86,4 +86,4 @@ async def seed_standard_sources(session, *, clock: Clock | None = None) -> int:
return len(STANDARD_SOURCE_SEEDS)
__all__ = ["STANDARD_SOURCE_SEEDS", "SeededSource", "seed_standard_sources"]
__all__ = ["STANDARD_SOURCE_SEEDS", "SeededSource", "seed_standard_sources"]

View File

@ -12,4 +12,4 @@ __all__ = [
"CachedExportWorker",
"ImmediateDeliveryWorker",
"SourceHealthWorker",
]
]

View File

@ -4,7 +4,7 @@ import asyncio
import logging
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
@ -29,9 +29,9 @@ class CachedEventRetentionWorker:
def __post_init__(self) -> None:
if self.history_ttl_seconds <= 0:
raise ValueError('history_ttl_seconds must be greater than zero')
raise ValueError("history_ttl_seconds must be greater than zero")
if self.poll_interval < 0:
raise ValueError('poll_interval must be greater than or equal to zero')
raise ValueError("poll_interval must be greater than or equal to zero")
async def run_once(self, *, as_of: datetime | None = None) -> int:
current = as_of or self.clock.now()
@ -40,11 +40,11 @@ class CachedEventRetentionWorker:
removed = await CachedEventRepository(uow.session).purge_older_than(cutoff)
if removed > 0:
logger.info(
'cache retention purge completed',
"cache retention purge completed",
extra=build_log_context(
channel='cache',
channel="cache",
deleted_count=removed,
cutoff=cutoff.isoformat().replace('+00:00', 'Z'),
cutoff=cutoff.isoformat().replace("+00:00", "Z"),
),
)
return removed
@ -62,4 +62,4 @@ class CachedEventRetentionWorker:
self._stop_requested = True
__all__ = ['CachedEventRetentionWorker']
__all__ = ["CachedEventRetentionWorker"]

View File

@ -11,8 +11,14 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from app.core.clock import Clock, SystemClock
from app.core.config import TransportSettings
from app.delivery.cached_packet_builder import CachedMessagePacketBuilder
from app.delivery.northbound_client import NorthboundClientProtocol, WebhookTransportClient
from app.storage.repositories import CachedEventDeliveryRepository, CachedEventRecord, TransportOutboxRepository
from app.delivery.northbound_client import (
NorthboundClientProtocol,
WebhookTransportClient,
)
from app.storage.repositories import (
CachedEventDeliveryRepository,
TransportOutboxRepository,
)
from app.storage.repositories.export_records import OutboxPacketRecord
from app.domain.enums import TransportPacketStatus
@ -41,9 +47,9 @@ class CachedExportWorker:
_stop_requested: bool = field(default=False, init=False, repr=False)
def __post_init__(self) -> None:
if self.transport.kind == 'webhook' and self.client is None:
if self.transport.kind == "webhook" and self.client is None:
if self.transport.url is None or self.transport.timeout_seconds is None:
raise ValueError('webhook transport requires url and timeout_seconds')
raise ValueError("webhook transport requires url and timeout_seconds")
self.client = WebhookTransportClient(
url=self.transport.url,
headers=self.transport.headers,
@ -55,7 +61,7 @@ class CachedExportWorker:
await self._ensure_delivery_rows()
await self._reconcile_prepared_rows()
processed = await self._process_existing_packets(now)
if self.transport.kind == 'none':
if self.transport.kind == "none":
return processed + await self._auto_deliver_none(now)
return processed + await self._prepare_and_send_due(now)
@ -83,7 +89,9 @@ class CachedExportWorker:
if not missing:
await session.rollback()
return
await repo.ensure_records(missing, period_seconds_by_transport=period_map)
await repo.ensure_records(
missing, period_seconds_by_transport=period_map
)
await session.commit()
if len(missing) < self.fetch_limit:
return
@ -163,10 +171,12 @@ class CachedExportWorker:
try:
async with self.outbox_session_factory() as outbox_session:
repo = TransportOutboxRepository(outbox_session)
await repo.save_packet(packet, cached_event_ids=[event.id for event in due_events])
await repo.save_packet(
packet, cached_event_ids=[event.id for event in due_events]
)
await repo.increment_counter(
transport_name=self.transport.name,
outcome='created',
outcome="created",
packet_count=1,
message_count=len(due_events),
updated_at=now,
@ -174,10 +184,12 @@ class CachedExportWorker:
await outbox_session.commit()
except Exception:
async with self.main_session_factory() as session:
await CachedEventDeliveryRepository(session).mark_undelivered_for_packet(
await CachedEventDeliveryRepository(
session
).mark_undelivered_for_packet(
packet_id=packet_id,
undelivered_at=now,
last_error='packet persistence failed',
last_error="packet persistence failed",
)
await session.commit()
raise
@ -187,7 +199,7 @@ class CachedExportWorker:
async def _deliver_packet(self, packet: OutboxPacketRecord, now: datetime) -> None:
if self.client is None:
raise RuntimeError('webhook transport requires a client')
raise RuntimeError("webhook transport requires a client")
async with self.outbox_session_factory() as outbox_session:
repo = TransportOutboxRepository(outbox_session)
await repo.mark_sending(packet.packet_id, locked_at=now)
@ -200,7 +212,9 @@ class CachedExportWorker:
except Exception as exc:
failure_at = self.clock.now()
async with self.main_session_factory() as session:
await CachedEventDeliveryRepository(session).mark_undelivered_for_packet(
await CachedEventDeliveryRepository(
session
).mark_undelivered_for_packet(
packet_id=packet.packet_id,
undelivered_at=failure_at,
last_error=_format_delivery_error(exc),
@ -210,7 +224,7 @@ class CachedExportWorker:
repo = TransportOutboxRepository(outbox_session)
await repo.increment_counter(
transport_name=self.transport.name,
outcome='failed',
outcome="failed",
packet_count=1,
message_count=packet.message_count,
updated_at=failure_at,
@ -230,10 +244,10 @@ class CachedExportWorker:
repo = TransportOutboxRepository(outbox_session)
await repo.increment_counter(
transport_name=self.transport.name,
outcome='sent',
outcome="sent",
packet_count=1,
message_count=packet.message_count,
updated_at=delivered_at,
)
await repo.delete_packet(packet.packet_id)
await outbox_session.commit()
await outbox_session.commit()

View File

@ -167,10 +167,3 @@ class ImmediateDeliveryWorker:
__all__ = ["ImmediateDeliveryWorker"]

View File

@ -63,4 +63,4 @@ async def run_migrations_online() -> None:
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())
asyncio.run(run_migrations_online())

View File

@ -13,7 +13,9 @@ UTC_TIMESTAMP = sa.String(40)
JSON_TEXT = sa.Text()
def _uuid_column(name: str, *, nullable: bool = False, primary_key: bool = False) -> sa.Column:
def _uuid_column(
name: str, *, nullable: bool = False, primary_key: bool = False
) -> sa.Column:
return sa.Column(name, UUID, primary_key=primary_key, nullable=nullable)
@ -21,8 +23,12 @@ def _timestamp_column(name: str, *, nullable: bool = False) -> sa.Column:
return sa.Column(name, UTC_TIMESTAMP, nullable=nullable)
def _json_column(name: str, *, nullable: bool = False, default: str = "{}") -> sa.Column:
return sa.Column(name, JSON_TEXT, nullable=nullable, server_default=sa.text(f"'{default}'"))
def _json_column(
name: str, *, nullable: bool = False, default: str = "{}"
) -> sa.Column:
return sa.Column(
name, JSON_TEXT, nullable=nullable, server_default=sa.text(f"'{default}'")
)
def upgrade() -> None:
@ -32,13 +38,17 @@ def upgrade() -> None:
sa.Column("source_key", sa.String(255), nullable=False),
sa.Column("source_kind", sa.String(64), nullable=False),
sa.Column("display_name", sa.String(255), nullable=False),
sa.Column("is_enabled", sa.Boolean(), nullable=False, server_default=sa.text("1")),
sa.Column(
"is_enabled", sa.Boolean(), nullable=False, server_default=sa.text("1")
),
_json_column("metadata_json"),
_timestamp_column("created_at"),
_timestamp_column("updated_at"),
sa.UniqueConstraint("source_key", name="uq_source_registry_source_key"),
)
op.create_index("ix_source_registry_source_kind", "source_registry", ["source_kind"])
op.create_index(
"ix_source_registry_source_kind", "source_registry", ["source_kind"]
)
op.create_table(
"source_health",
@ -50,7 +60,9 @@ def upgrade() -> None:
_json_column("details_json"),
_timestamp_column("created_at"),
_timestamp_column("updated_at"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_source_health_source_id"),
sa.ForeignKeyConstraint(
["source_id"], ["source_registry.id"], name="fk_source_health_source_id"
),
)
op.create_index("ix_source_health_status", "source_health", ["status"])
@ -67,7 +79,9 @@ def upgrade() -> None:
_json_column("correlation_json"),
_timestamp_column("created_at"),
_timestamp_column("updated_at"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_wifi_state_latest_source_id"),
sa.ForeignKeyConstraint(
["source_id"], ["source_registry.id"], name="fk_wifi_state_latest_source_id"
),
sa.UniqueConstraint("state_id", name="uq_wifi_state_latest_state_id"),
)
op.create_index("ix_wifi_state_latest_status", "wifi_state_latest", ["status"])
@ -84,9 +98,13 @@ def upgrade() -> None:
sa.Column("priority", sa.String(32), nullable=False),
_json_column("payload_json"),
_json_column("correlation_json"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_wifi_events_source_id"),
sa.ForeignKeyConstraint(
["source_id"], ["source_registry.id"], name="fk_wifi_events_source_id"
),
)
op.create_index(
"ix_wifi_events_source_created_at", "wifi_events", ["source_id", "created_at"]
)
op.create_index("ix_wifi_events_source_created_at", "wifi_events", ["source_id", "created_at"])
op.create_index("ix_wifi_events_event_type", "wifi_events", ["event_type"])
op.create_table(
@ -100,9 +118,17 @@ def upgrade() -> None:
sa.Column("priority", sa.String(32), nullable=False),
_json_column("payload_json"),
_json_column("correlation_json"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_diagnostic_log_events_source_id"),
sa.ForeignKeyConstraint(
["source_id"],
["source_registry.id"],
name="fk_diagnostic_log_events_source_id",
),
)
op.create_index(
"ix_diagnostic_log_events_process_created_at",
"diagnostic_log_events",
["process_name", "created_at"],
)
op.create_index("ix_diagnostic_log_events_process_created_at", "diagnostic_log_events", ["process_name", "created_at"])
op.create_table(
"location_snapshots",
@ -119,9 +145,17 @@ def upgrade() -> None:
sa.Column("priority", sa.String(32), nullable=False),
_json_column("payload_json"),
_json_column("correlation_json"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_location_snapshots_source_id"),
sa.ForeignKeyConstraint(
["source_id"],
["source_registry.id"],
name="fk_location_snapshots_source_id",
),
)
op.create_index(
"ix_location_snapshots_source_captured_at",
"location_snapshots",
["source_id", "captured_at"],
)
op.create_index("ix_location_snapshots_source_captured_at", "location_snapshots", ["source_id", "captured_at"])
op.create_table(
"commands",
@ -137,9 +171,15 @@ def upgrade() -> None:
_json_column("arguments_json"),
sa.Column("result_json", sa.Text(), nullable=True),
_json_column("correlation_json"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_commands_source_id"),
sa.ForeignKeyConstraint(
["source_id"], ["source_registry.id"], name="fk_commands_source_id"
),
)
op.create_index(
"ix_commands_source_status_created_at",
"commands",
["source_id", "status", "created_at"],
)
op.create_index("ix_commands_source_status_created_at", "commands", ["source_id", "status", "created_at"])
op.create_table(
"derived_events",
@ -155,10 +195,20 @@ def upgrade() -> None:
sa.Column("priority", sa.String(32), nullable=False),
_json_column("payload_json"),
_json_column("correlation_json"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_derived_events_source_id"),
sa.ForeignKeyConstraint(
["source_id"], ["source_registry.id"], name="fk_derived_events_source_id"
),
)
op.create_index(
"ix_derived_events_related_entity",
"derived_events",
["related_entity_kind", "related_entity_id"],
)
op.create_index(
"ix_derived_events_source_created_at",
"derived_events",
["source_id", "created_at"],
)
op.create_index("ix_derived_events_related_entity", "derived_events", ["related_entity_kind", "related_entity_id"])
op.create_index("ix_derived_events_source_created_at", "derived_events", ["source_id", "created_at"])
op.create_table(
"outbox",
@ -171,14 +221,20 @@ def upgrade() -> None:
sa.Column("priority", sa.String(32), nullable=False),
_timestamp_column("created_at"),
_timestamp_column("available_at"),
sa.Column("attempt_count", sa.Integer(), nullable=False, server_default=sa.text("0")),
sa.Column(
"attempt_count", sa.Integer(), nullable=False, server_default=sa.text("0")
),
_timestamp_column("last_attempt_at", nullable=True),
sa.Column("last_error", sa.Text(), nullable=True),
_json_column("payload_json"),
_json_column("correlation_json"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_outbox_source_id"),
sa.ForeignKeyConstraint(
["source_id"], ["source_registry.id"], name="fk_outbox_source_id"
),
)
op.create_index(
"ix_outbox_status_available_at", "outbox", ["status", "available_at"]
)
op.create_index("ix_outbox_status_available_at", "outbox", ["status", "available_at"])
op.create_index("ix_outbox_source_status", "outbox", ["source_id", "status"])
op.create_table(
@ -188,7 +244,9 @@ def upgrade() -> None:
sa.Column("cursor_value", sa.Text(), nullable=False),
_timestamp_column("updated_at"),
_json_column("details_json"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_journal_cursors_source_id"),
sa.ForeignKeyConstraint(
["source_id"], ["source_registry.id"], name="fk_journal_cursors_source_id"
),
)
op.create_index("ix_journal_cursors_source_id", "journal_cursors", ["source_id"])
@ -208,10 +266,15 @@ def downgrade() -> None:
op.drop_index("ix_commands_source_status_created_at", table_name="commands")
op.drop_table("commands")
op.drop_index("ix_location_snapshots_source_captured_at", table_name="location_snapshots")
op.drop_index(
"ix_location_snapshots_source_captured_at", table_name="location_snapshots"
)
op.drop_table("location_snapshots")
op.drop_index("ix_diagnostic_log_events_process_created_at", table_name="diagnostic_log_events")
op.drop_index(
"ix_diagnostic_log_events_process_created_at",
table_name="diagnostic_log_events",
)
op.drop_table("diagnostic_log_events")
op.drop_index("ix_wifi_events_event_type", table_name="wifi_events")
@ -225,4 +288,4 @@ def downgrade() -> None:
op.drop_table("source_health")
op.drop_index("ix_source_registry_source_kind", table_name="source_registry")
op.drop_table("source_registry")
op.drop_table("source_registry")

View File

@ -13,7 +13,9 @@ UTC_TIMESTAMP = sa.String(40)
JSON_TEXT = sa.Text()
def _uuid_column(name: str, *, nullable: bool = False, primary_key: bool = False) -> sa.Column:
def _uuid_column(
name: str, *, nullable: bool = False, primary_key: bool = False
) -> sa.Column:
return sa.Column(name, UUID, primary_key=primary_key, nullable=nullable)
@ -21,8 +23,12 @@ def _timestamp_column(name: str, *, nullable: bool = False) -> sa.Column:
return sa.Column(name, UTC_TIMESTAMP, nullable=nullable)
def _json_column(name: str, *, nullable: bool = False, default: str = "{}") -> sa.Column:
return sa.Column(name, JSON_TEXT, nullable=nullable, server_default=sa.text(f"'{default}'"))
def _json_column(
name: str, *, nullable: bool = False, default: str = "{}"
) -> sa.Column:
return sa.Column(
name, JSON_TEXT, nullable=nullable, server_default=sa.text(f"'{default}'")
)
def upgrade() -> None:
@ -39,10 +45,16 @@ def upgrade() -> None:
_json_column("payload_json"),
_json_column("acl_json"),
sa.Column("mark", sa.String(128), nullable=True),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_cached_events_source_id"),
sa.ForeignKeyConstraint(
["source_id"], ["source_registry.id"], name="fk_cached_events_source_id"
),
)
op.create_index("ix_cached_events_expires_at", "cached_events", ["expires_at"])
op.create_index("ix_cached_events_source_created_at", "cached_events", ["source_id", "created_at"])
op.create_index(
"ix_cached_events_source_created_at",
"cached_events",
["source_id", "created_at"],
)
def downgrade() -> None:

View File

@ -13,7 +13,9 @@ UTC_TIMESTAMP = sa.String(40)
JSON_TEXT = sa.Text()
def _uuid_column(name: str, *, nullable: bool = False, primary_key: bool = False) -> sa.Column:
def _uuid_column(
name: str, *, nullable: bool = False, primary_key: bool = False
) -> sa.Column:
return sa.Column(name, UUID, primary_key=primary_key, nullable=nullable)
@ -21,8 +23,12 @@ def _timestamp_column(name: str, *, nullable: bool = False) -> sa.Column:
return sa.Column(name, UTC_TIMESTAMP, nullable=nullable)
def _json_column(name: str, *, nullable: bool = False, default: str = "{}") -> sa.Column:
return sa.Column(name, JSON_TEXT, nullable=nullable, server_default=sa.text(f"'{default}'"))
def _json_column(
name: str, *, nullable: bool = False, default: str = "{}"
) -> sa.Column:
return sa.Column(
name, JSON_TEXT, nullable=nullable, server_default=sa.text(f"'{default}'")
)
def upgrade() -> None:
@ -36,7 +42,11 @@ def upgrade() -> None:
_timestamp_column("created_at"),
_timestamp_column("updated_at"),
sa.UniqueConstraint("source_key", name="uq_wifi_scan_snapshots_source_key"),
sa.ForeignKeyConstraint(["source_id"], ["source_registry.id"], name="fk_wifi_scan_snapshots_source_id"),
sa.ForeignKeyConstraint(
["source_id"],
["source_registry.id"],
name="fk_wifi_scan_snapshots_source_id",
),
)
op.create_index(
"ix_wifi_scan_snapshots_refreshed_at",
@ -46,5 +56,7 @@ def upgrade() -> None:
def downgrade() -> None:
op.drop_index("ix_wifi_scan_snapshots_refreshed_at", table_name="wifi_scan_snapshots")
op.drop_index(
"ix_wifi_scan_snapshots_refreshed_at", table_name="wifi_scan_snapshots"
)
op.drop_table("wifi_scan_snapshots")

View File

@ -10,11 +10,21 @@ depends_on = None
def upgrade() -> None:
op.add_column("cached_events", sa.Column("raw_event_name", sa.String(128), nullable=True))
op.add_column("cached_events", sa.Column("event_origin", sa.String(16), nullable=True))
op.add_column("cached_events", sa.Column("derived_from", sa.String(128), nullable=True))
op.execute("UPDATE cached_events SET raw_event_name = event_label WHERE raw_event_name IS NULL OR trim(raw_event_name) = ''")
op.execute("UPDATE cached_events SET event_origin = 'raw' WHERE event_origin IS NULL OR trim(event_origin) = ''")
op.add_column(
"cached_events", sa.Column("raw_event_name", sa.String(128), nullable=True)
)
op.add_column(
"cached_events", sa.Column("event_origin", sa.String(16), nullable=True)
)
op.add_column(
"cached_events", sa.Column("derived_from", sa.String(128), nullable=True)
)
op.execute(
"UPDATE cached_events SET raw_event_name = event_label WHERE raw_event_name IS NULL OR trim(raw_event_name) = ''"
)
op.execute(
"UPDATE cached_events SET event_origin = 'raw' WHERE event_origin IS NULL OR trim(event_origin) = ''"
)
def downgrade() -> None:

View File

@ -21,10 +21,12 @@ def upgrade() -> None:
sa.Column("delivered_at", sa.String(length=40), nullable=True),
sa.Column("undelivered_at", sa.String(length=40), nullable=True),
sa.Column("last_error", sa.Text(), nullable=True),
sa.ForeignKeyConstraint(["cached_event_id"], ["cached_events.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(
["cached_event_id"], ["cached_events.id"], ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("cached_event_id"),
)
def downgrade() -> None:
op.drop_table("cached_event_delivery")
op.drop_table("cached_event_delivery")

View File

@ -3,4 +3,3 @@
__all__ = ["__version__"]
__version__ = "0.1.0"

View File

@ -7,7 +7,10 @@ from datetime import datetime, timezone
from pathlib import Path
from fastapi import Body, FastAPI, HTTPException, Request, status
from fastapi.openapi.docs import get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html
from fastapi.openapi.docs import (
get_swagger_ui_html,
get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles
from .models import AgentConfig, EventRecord, InterfaceState
@ -49,7 +52,9 @@ def _event_to_payload(
"event_type": event.event_type,
"payload": json.loads(event.payload_json),
"created_at": _iso(event.created_at),
"ttl_remaining_seconds": _ttl_remaining_seconds(event.created_at, ttl_seconds, now=now),
"ttl_remaining_seconds": _ttl_remaining_seconds(
event.created_at, ttl_seconds, now=now
),
}
@ -63,7 +68,9 @@ def _state_to_payload(state: InterfaceState) -> dict[str, object]:
}
def _related_object_to_payload(interface: str, snapshot: dict[str, object]) -> dict[str, object]:
def _related_object_to_payload(
interface: str, snapshot: dict[str, object]
) -> dict[str, object]:
return {
"interface": interface,
**snapshot,
@ -89,13 +96,20 @@ def _static_dir() -> Path:
def _require_api_key(config: AgentConfig, request: Request) -> None:
expected = config.api.api_key
if not expected:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="API key is not configured")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="API key is not configured",
)
supplied = request.headers.get(config.api.api_key_header)
if supplied != expected:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key"
)
def create_app(config: AgentConfig, store: SqliteStore, supervisor: ConnectionSupervisor) -> FastAPI:
def create_app(
config: AgentConfig, store: SqliteStore, supervisor: ConnectionSupervisor
) -> FastAPI:
@asynccontextmanager
async def lifespan(app: FastAPI):
await store.open()
@ -110,7 +124,13 @@ def create_app(config: AgentConfig, store: SqliteStore, supervisor: ConnectionSu
await asyncio.gather(task, return_exceptions=True)
await store.close()
app = FastAPI(title="dbus-agent", version="0.1.0", lifespan=lifespan, docs_url=None, redoc_url=None)
app = FastAPI(
title="dbus-agent",
version="0.1.0",
lifespan=lifespan,
docs_url=None,
redoc_url=None,
)
app.mount("/static", StaticFiles(directory=_static_dir()), name="static")
app.state.config = config
@ -150,242 +170,390 @@ def create_app(config: AgentConfig, store: SqliteStore, supervisor: ConnectionSu
@app.get("/interfaces/{ifname}/state")
async def get_state(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
state = await supervisor.client.read_interface_state(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
await store.touch_interface(state)
return _state_to_payload(state)
@app.get("/interfaces/{ifname}/current_bss")
async def get_current_bss(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
snapshot = await supervisor.client.read_current_bss(ifname)
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
if snapshot is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Current BSS not found")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Current BSS not found"
)
return _related_object_to_payload(ifname, snapshot)
@app.get("/interfaces/{ifname}/current_network")
async def get_current_network(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
snapshot = await supervisor.client.read_current_network(ifname)
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
if snapshot is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Current network not found")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Current network not found",
)
return _related_object_to_payload(ifname, snapshot)
@app.get("/interfaces/{ifname}/signal_poll")
async def signal_poll(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
properties = await supervisor.client.signal_poll(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "properties": properties}
@app.post("/interfaces/{ifname}/scan", status_code=status.HTTP_202_ACCEPTED)
async def scan(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.scan(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/disconnect", status_code=status.HTTP_202_ACCEPTED)
async def disconnect(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.disconnect_interface(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/reattach", status_code=status.HTTP_202_ACCEPTED)
async def reattach(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.reattach(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/reassociate", status_code=status.HTTP_202_ACCEPTED)
async def reassociate(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.reassociate(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/reconnect", status_code=status.HTTP_202_ACCEPTED)
async def reconnect(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.reconnect(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/eap_logoff", status_code=status.HTTP_202_ACCEPTED)
async def eap_logoff(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.eap_logoff(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/eap_logon", status_code=status.HTTP_202_ACCEPTED)
async def eap_logon(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.eap_logon(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except InterfaceConflictError as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/subscribe_probe_req", status_code=status.HTTP_202_ACCEPTED)
@app.post(
"/interfaces/{ifname}/subscribe_probe_req", status_code=status.HTTP_202_ACCEPTED
)
async def subscribe_probe_req(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.subscribe_probe_req(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/unsubscribe_probe_req", status_code=status.HTTP_202_ACCEPTED)
@app.post(
"/interfaces/{ifname}/unsubscribe_probe_req",
status_code=status.HTTP_202_ACCEPTED,
)
async def unsubscribe_probe_req(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
await supervisor.client.unsubscribe_probe_req(ifname)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "requested": True}
@app.post("/interfaces/{ifname}/add_network", status_code=status.HTTP_201_CREATED)
async def add_network(ifname: str, payload: dict[str, object] = Body(default_factory=dict)) -> dict[str, object]:
async def add_network(
ifname: str, payload: dict[str, object] = Body(default_factory=dict)
) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
network_path = await supervisor.client.add_network(ifname, payload)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
) from exc
except PermissionError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)
) from exc
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
return {"interface": ifname, "network": network_path}
@app.get("/interfaces/{ifname}/scan_results")
async def get_scan_results(ifname: str) -> dict[str, object]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
try:
cached = await store.get_scan_results(ifname)
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
if cached is None:
try:
results = await supervisor.client.read_scan_results(ifname)
except RuntimeError as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
await store.replace_scan_results(ifname, results)
return _scan_results_to_payload(ifname, results, None)
return _scan_results_to_payload(
ifname,
cached["results"],
cached.get("refreshed_at") if isinstance(cached.get("refreshed_at"), datetime) else None,
(
cached.get("refreshed_at")
if isinstance(cached.get("refreshed_at"), datetime)
else None
),
)
@app.get("/interfaces/{ifname}/events")
async def get_events(ifname: str, limit: int = 100) -> list[dict[str, object]]:
if ifname != config.interface:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured")
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Interface not configured"
)
events = await store.list_events(ifname, limit=limit)
return [_event_to_payload(event, ttl_seconds=config.retention.record_ttl_seconds) for event in events]
return [
_event_to_payload(event, ttl_seconds=config.retention.record_ttl_seconds)
for event in events
]
@app.post("/commands")
async def commands(request: Request, payload: dict[str, object] = Body(default_factory=dict)) -> dict[str, object]:
async def commands(
request: Request, payload: dict[str, object] = Body(default_factory=dict)
) -> dict[str, object]:
_require_api_key(config, request)
raise HTTPException(
status_code=status.HTTP_501_NOT_IMPLEMENTED,
detail={"message": "Command execution is not implemented yet", "payload": payload},
detail={
"message": "Command execution is not implemented yet",
"payload": payload,
},
)
return app

View File

@ -10,7 +10,6 @@ from typing import Any
import httpx
EXIT_SUCCESS = 0
EXIT_USAGE = 2
EXIT_TRANSPORT = 3
@ -52,11 +51,19 @@ def load_cli_settings(namespace: argparse.Namespace) -> CliSettings:
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="dbus-agent.cli", description="Console client for dbus-agent REST API")
parser.add_argument("--base-url", default=_env("DBUS_AGENT_API_BASE_URL", "http://127.0.0.1:8080"))
parser = argparse.ArgumentParser(
prog="dbus-agent.cli", description="Console client for dbus-agent REST API"
)
parser.add_argument(
"--base-url", default=_env("DBUS_AGENT_API_BASE_URL", "http://127.0.0.1:8080")
)
parser.add_argument("--api-key", default=_env("DBUS_AGENT_API_KEY"))
parser.add_argument("--timeout", type=float, default=float(_env("DBUS_AGENT_API_TIMEOUT", "10")))
parser.add_argument("--output", choices=("text", "json"), default=_env("DBUS_AGENT_OUTPUT", "text"))
parser.add_argument(
"--timeout", type=float, default=float(_env("DBUS_AGENT_API_TIMEOUT", "10"))
)
parser.add_argument(
"--output", choices=("text", "json"), default=_env("DBUS_AGENT_OUTPUT", "text")
)
parser.add_argument(
"--api-key-header",
default=_env("DBUS_AGENT_API_KEY_HEADER", "X-API-Key"),
@ -74,19 +81,29 @@ def build_parser() -> argparse.ArgumentParser:
events.add_argument("ifname", help="Interface name")
events.add_argument("--limit", type=int, default=100)
scan_results = subparsers.add_parser("scan-results", help="Show scan results for an interface")
scan_results = subparsers.add_parser(
"scan-results", help="Show scan results for an interface"
)
scan_results.add_argument("ifname", help="Interface name")
command = subparsers.add_parser("command", aliases=["commands"], help="Send a command payload")
command.add_argument("--payload", default="{}", help="JSON payload sent to POST /commands")
command = subparsers.add_parser(
"command", aliases=["commands"], help="Send a command payload"
)
command.add_argument(
"--payload", default="{}", help="JSON payload sent to POST /commands"
)
return parser
class ApiClient:
def __init__(self, settings: CliSettings, client: httpx.Client | None = None) -> None:
def __init__(
self, settings: CliSettings, client: httpx.Client | None = None
) -> None:
self._settings = settings
self._client = client or httpx.Client(base_url=settings.base_url, timeout=settings.timeout_seconds)
self._client = client or httpx.Client(
base_url=settings.base_url, timeout=settings.timeout_seconds
)
self._owns_client = client is None
def close(self) -> None:
@ -138,7 +155,9 @@ def _run_command(namespace: argparse.Namespace, client: ApiClient) -> CliResult:
else: # pragma: no cover - argparse prevents this branch
raise ValueError(f"Unknown command: {namespace.command}")
return CliResult(status_code=response.status_code, payload=_decode_payload(response))
return CliResult(
status_code=response.status_code, payload=_decode_payload(response)
)
def _scalar(value: Any) -> str:
@ -189,7 +208,9 @@ def _render_text(command: str, payload: Any) -> str:
if field in event:
lines.append(f" {field}: {_scalar(event[field])}")
if "ttl_remaining_seconds" in event:
lines.append(f" ttl_remaining_seconds: {_scalar(event['ttl_remaining_seconds'])}")
lines.append(
f" ttl_remaining_seconds: {_scalar(event['ttl_remaining_seconds'])}"
)
if "payload" in event:
lines.append(" payload:")
lines.extend(_text_lines(event["payload"], 2))
@ -264,16 +285,28 @@ def run(
try:
namespace = parser.parse_args(argv)
settings = load_cli_settings(namespace)
client = client_factory(settings) if client_factory is not None else ApiClient(settings)
client = (
client_factory(settings)
if client_factory is not None
else ApiClient(settings)
)
try:
result = _run_command(namespace, client)
finally:
client.close()
command_name = "command" if namespace.command == "commands" else namespace.command
command_name = (
"command" if namespace.command == "commands" else namespace.command
)
if 200 <= result.status_code < 300:
print(_render_success(command_name, settings.output, result.payload), file=stdout)
print(
_render_success(command_name, settings.output, result.payload),
file=stdout,
)
return EXIT_SUCCESS
print(_render_error(settings.output, result.status_code, result.payload), file=stderr)
print(
_render_error(settings.output, result.status_code, result.payload),
file=stderr,
)
return _exit_code_for_status(result.status_code)
except ValueError as exc:
print(f"{parser.prog}: error: {exc}", file=stderr)

View File

@ -58,7 +58,9 @@ def _as_positive_float(value: str | float | None, default: float) -> float:
return parsed
def _as_event_type_list(value: object | None, default: tuple[str, ...] = ()) -> tuple[str, ...]:
def _as_event_type_list(
value: object | None, default: tuple[str, ...] = ()
) -> tuple[str, ...]:
if value is None or value == "":
return default
if isinstance(value, str):
@ -89,7 +91,9 @@ def load_agent_config(config_path: Path, env_path: Path | None = None) -> AgentC
interface = env_vars.get("DBUS_AGENT_INTERFACE") or data.get("interface")
if not interface:
raise ValueError("interface is required in the YAML config or in DBUS_AGENT_INTERFACE")
raise ValueError(
"interface is required in the YAML config or in DBUS_AGENT_INTERFACE"
)
dbus_data = data.get("dbus", {}) or {}
database_data = data.get("database", {}) or {}
@ -99,26 +103,38 @@ def load_agent_config(config_path: Path, env_path: Path | None = None) -> AgentC
event_filter_data = data.get("event_filter", {}) or {}
dbus = DbusSettings(
service=env_vars.get("DBUS_AGENT_DBUS_SERVICE", dbus_data.get("service", "fi.w1.wpa_supplicant1")),
service=env_vars.get(
"DBUS_AGENT_DBUS_SERVICE", dbus_data.get("service", "fi.w1.wpa_supplicant1")
),
object_path=env_vars.get(
"DBUS_AGENT_DBUS_OBJECT_PATH", dbus_data.get("object_path", "/fi/w1/wpa_supplicant1")
"DBUS_AGENT_DBUS_OBJECT_PATH",
dbus_data.get("object_path", "/fi/w1/wpa_supplicant1"),
),
)
database_path = env_vars.get("DBUS_AGENT_DATABASE_PATH") or database_data.get("path")
database_path = env_vars.get("DBUS_AGENT_DATABASE_PATH") or database_data.get(
"path"
)
if not database_path:
database_path = "/var/lib/dbus-agent/dbus-agent.sqlite3"
api = ApiSettings(
host=env_vars.get("DBUS_AGENT_API_HOST", api_data.get("host", "127.0.0.1")),
port=_as_int(env_vars.get("DBUS_AGENT_API_PORT", api_data.get("port", 8080)), 8080),
api_key_header=env_vars.get("DBUS_AGENT_API_KEY_HEADER", api_data.get("api_key_header", "X-API-Key")),
port=_as_int(
env_vars.get("DBUS_AGENT_API_PORT", api_data.get("port", 8080)), 8080
),
api_key_header=env_vars.get(
"DBUS_AGENT_API_KEY_HEADER", api_data.get("api_key_header", "X-API-Key")
),
api_key=env_vars.get("DBUS_AGENT_API_KEY", api_data.get("api_key")),
)
heartbeat = HeartbeatSettings(
interval_seconds=_as_float(
env_vars.get("DBUS_AGENT_HEARTBEAT_INTERVAL", heartbeat_data.get("interval_seconds", 10.0)),
env_vars.get(
"DBUS_AGENT_HEARTBEAT_INTERVAL",
heartbeat_data.get("interval_seconds", 10.0),
),
10.0,
),
reconnect_initial_delay_seconds=_as_float(
@ -129,7 +145,10 @@ def load_agent_config(config_path: Path, env_path: Path | None = None) -> AgentC
1.0,
),
reconnect_max_delay_seconds=_as_float(
env_vars.get("DBUS_AGENT_RECONNECT_MAX_DELAY", heartbeat_data.get("reconnect_max_delay_seconds", 30.0)),
env_vars.get(
"DBUS_AGENT_RECONNECT_MAX_DELAY",
heartbeat_data.get("reconnect_max_delay_seconds", 30.0),
),
30.0,
),
)

View File

@ -20,7 +20,9 @@ except ImportError: # pragma: no cover - exercised only when dependency is miss
class EventCallback(Protocol):
async def __call__(self, event: EventRecord) -> None: # pragma: no cover - protocol definition
async def __call__(
self, event: EventRecord
) -> None: # pragma: no cover - protocol definition
...
@ -69,7 +71,11 @@ def _is_invalid_args_error(exc: Exception) -> bool:
text = str(getattr(exc, "text", ""))
message = " ".join(part for part in (name, text, str(exc)) if part)
lowered = message.lower()
return "invalidargs" in name.lower() or "invalid args" in lowered or "invalid argument" in lowered
return (
"invalidargs" in name.lower()
or "invalid args" in lowered
or "invalid argument" in lowered
)
def _dbus_variant(signature: str, value: object) -> object:
@ -141,8 +147,12 @@ class WpaSupplicantDbusClient:
self._loop = asyncio.get_running_loop()
bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
introspection = await bus.introspect(self._config.dbus.service, self._config.dbus.object_path)
proxy = bus.get_proxy_object(self._config.dbus.service, self._config.dbus.object_path, introspection)
introspection = await bus.introspect(
self._config.dbus.service, self._config.dbus.object_path
)
proxy = bus.get_proxy_object(
self._config.dbus.service, self._config.dbus.object_path, introspection
)
wpa_supplicant = proxy.get_interface(self._config.dbus.service)
@ -152,7 +162,9 @@ class WpaSupplicantDbusClient:
self._bus = bus
await self._attach_selected_interface_from_root(wpa_supplicant)
self._snapshot = DbusConnectionSnapshot(connected=True, last_ping_at=datetime.now(timezone.utc))
self._snapshot = DbusConnectionSnapshot(
connected=True, last_ping_at=datetime.now(timezone.utc)
)
await self.emit_snapshot(
"StartupSnapshot",
{
@ -168,29 +180,43 @@ class WpaSupplicantDbusClient:
self._bus = None
self._attached_interface_paths.clear()
self._selected_interface_path = None
self._snapshot = DbusConnectionSnapshot(connected=False, last_error=self._snapshot.last_error)
self._snapshot = DbusConnectionSnapshot(
connected=False, last_error=self._snapshot.last_error
)
async def ping(self) -> None:
if self._bus is None:
raise RuntimeError("dbus client is not connected")
await self._bus.introspect(self._config.dbus.service, self._config.dbus.object_path)
self._snapshot = DbusConnectionSnapshot(connected=True, last_ping_at=datetime.now(timezone.utc))
await self._bus.introspect(
self._config.dbus.service, self._config.dbus.object_path
)
self._snapshot = DbusConnectionSnapshot(
connected=True, last_ping_at=datetime.now(timezone.utc)
)
async def read_interface_state(self, ifname: str) -> InterfaceState:
if self._bus is None:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_properties = await self._read_properties(interface_path, f"{self._config.dbus.service}.Interface")
interface_properties = await self._read_properties(
interface_path, f"{self._config.dbus.service}.Interface"
)
state = await self._read_interface_state_value(interface_path)
details = {key: value for key, value in interface_properties.items() if key not in {"CurrentBSS", "CurrentNetwork"}}
details = {
key: value
for key, value in interface_properties.items()
if key not in {"CurrentBSS", "CurrentNetwork"}
}
return InterfaceState(
interface=ifname,
status=str(state),
last_event_at=None,
last_heartbeat_at=self._snapshot.last_ping_at,
details_json=json.dumps(_normalize_dbus_value(details), sort_keys=True, default=str),
details_json=json.dumps(
_normalize_dbus_value(details), sort_keys=True, default=str
),
)
async def read_current_bss(
@ -211,35 +237,47 @@ class WpaSupplicantDbusClient:
if interface_properties is None:
interface_properties = await self._read_interface_properties(ifname)
current_network = interface_properties.get("CurrentNetwork")
return await self._read_related_object(current_network, "fi.w1.wpa_supplicant1.Network")
return await self._read_related_object(
current_network, "fi.w1.wpa_supplicant1.Network"
)
async def signal_poll(self, ifname: str) -> dict[str, object]:
if self._bus is None:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
snapshot = await interface.call_signal_poll()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied signal poll request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied signal poll request for {ifname}"
) from exc
if _is_interface_disabled_error(exc) or _is_not_connected_error(exc):
raise InterfaceConflictError(f"interface {ifname} cannot be signal-polled in its current state: {exc}") from exc
raise InterfaceConflictError(
f"interface {ifname} cannot be signal-polled in its current state: {exc}"
) from exc
raise RuntimeError(f"failed to signal poll {ifname}: {exc}") from exc
raise
normalized = _normalize_dbus_value(snapshot)
if not isinstance(normalized, dict):
raise RuntimeError(f"failed to signal poll {ifname}: unexpected response type {type(normalized).__name__}")
raise RuntimeError(
f"failed to signal poll {ifname}: unexpected response type {type(normalized).__name__}"
)
return normalized
async def read_scan_results(
@ -260,7 +298,9 @@ class WpaSupplicantDbusClient:
paths = list(bss_paths)
results: list[dict[str, object]] = []
for object_path in paths:
snapshot = await self._read_related_object(object_path, "fi.w1.wpa_supplicant1.BSS")
snapshot = await self._read_related_object(
object_path, "fi.w1.wpa_supplicant1.BSS"
)
if snapshot is not None:
results.append(snapshot)
return results
@ -270,20 +310,26 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_scan({"Type": _dbus_variant("s", "active")})
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied scan request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied scan request for {ifname}"
) from exc
raise RuntimeError(f"failed to start scan for {ifname}: {exc}") from exc
raise
@ -292,20 +338,26 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_disconnect()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied disconnect request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied disconnect request for {ifname}"
) from exc
raise RuntimeError(f"failed to disconnect {ifname}: {exc}") from exc
raise
@ -314,22 +366,30 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_reattach()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied reattach request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied reattach request for {ifname}"
) from exc
if _is_interface_disabled_error(exc) or _is_not_connected_error(exc):
raise InterfaceConflictError(f"interface {ifname} cannot be reattached in its current state: {exc}") from exc
raise InterfaceConflictError(
f"interface {ifname} cannot be reattached in its current state: {exc}"
) from exc
raise RuntimeError(f"failed to reattach {ifname}: {exc}") from exc
raise
@ -338,22 +398,30 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_reconnect()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied reconnect request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied reconnect request for {ifname}"
) from exc
if _is_interface_disabled_error(exc) or _is_not_connected_error(exc):
raise InterfaceConflictError(f"interface {ifname} cannot be reconnected in its current state: {exc}") from exc
raise InterfaceConflictError(
f"interface {ifname} cannot be reconnected in its current state: {exc}"
) from exc
raise RuntimeError(f"failed to reconnect {ifname}: {exc}") from exc
raise
@ -362,22 +430,30 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_eap_logoff()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied EAP logoff request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied EAP logoff request for {ifname}"
) from exc
if _is_interface_disabled_error(exc) or _is_not_connected_error(exc):
raise InterfaceConflictError(f"interface {ifname} cannot be logged off in its current state: {exc}") from exc
raise InterfaceConflictError(
f"interface {ifname} cannot be logged off in its current state: {exc}"
) from exc
raise RuntimeError(f"failed to log off {ifname}: {exc}") from exc
raise
@ -386,22 +462,30 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_eap_logon()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied EAP logon request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied EAP logon request for {ifname}"
) from exc
if _is_interface_disabled_error(exc) or _is_not_connected_error(exc):
raise InterfaceConflictError(f"interface {ifname} cannot be logged on in its current state: {exc}") from exc
raise InterfaceConflictError(
f"interface {ifname} cannot be logged on in its current state: {exc}"
) from exc
raise RuntimeError(f"failed to log on {ifname}: {exc}") from exc
raise
@ -410,21 +494,29 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_subscribe_probe_req()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied subscribe probe request for {ifname}") from exc
raise RuntimeError(f"failed to subscribe to probe requests for {ifname}: {exc}") from exc
raise PermissionError(
f"D-Bus policy denied subscribe probe request for {ifname}"
) from exc
raise RuntimeError(
f"failed to subscribe to probe requests for {ifname}: {exc}"
) from exc
raise
async def unsubscribe_probe_req(self, ifname: str) -> None:
@ -432,21 +524,29 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_unsubscribe_probe_req()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied unsubscribe probe request for {ifname}") from exc
raise RuntimeError(f"failed to unsubscribe from probe requests for {ifname}: {exc}") from exc
raise PermissionError(
f"D-Bus policy denied unsubscribe probe request for {ifname}"
) from exc
raise RuntimeError(
f"failed to unsubscribe from probe requests for {ifname}: {exc}"
) from exc
raise
async def reassociate(self, ifname: str) -> None:
@ -454,22 +554,30 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
await interface.call_reassociate()
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied reassociate request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied reassociate request for {ifname}"
) from exc
if _is_interface_disabled_error(exc):
raise InterfaceConflictError(f"interface {ifname} cannot be reassociated in its current state: {exc}") from exc
raise InterfaceConflictError(
f"interface {ifname} cannot be reassociated in its current state: {exc}"
) from exc
raise RuntimeError(f"failed to reassociate {ifname}: {exc}") from exc
raise
@ -478,13 +586,17 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
interface_path = await self._get_interface_path(ifname)
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
encoded_args = _json_to_dbus_args(args)
try:
@ -492,36 +604,54 @@ class WpaSupplicantDbusClient:
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
if _is_access_denied_error(exc):
raise PermissionError(f"D-Bus policy denied add network request for {ifname}") from exc
raise PermissionError(
f"D-Bus policy denied add network request for {ifname}"
) from exc
if _is_invalid_args_error(exc):
raise ValueError(f"invalid network configuration for {ifname}: {exc}") from exc
raise RuntimeError(f"failed to add network for {ifname}: {exc}") from exc
raise ValueError(
f"invalid network configuration for {ifname}: {exc}"
) from exc
raise RuntimeError(
f"failed to add network for {ifname}: {exc}"
) from exc
raise
if network_path is None:
raise RuntimeError(f"failed to add network for {ifname}: empty network path returned")
raise RuntimeError(
f"failed to add network for {ifname}: empty network path returned"
)
return str(network_path)
async def _get_interface_path(self, ifname: str) -> str:
root_introspection = await self._bus.introspect(self._config.dbus.service, self._config.dbus.object_path)
root_proxy = self._bus.get_proxy_object(self._config.dbus.service, self._config.dbus.object_path, root_introspection)
root_introspection = await self._bus.introspect(
self._config.dbus.service, self._config.dbus.object_path
)
root_proxy = self._bus.get_proxy_object(
self._config.dbus.service, self._config.dbus.object_path, root_introspection
)
root = root_proxy.get_interface(self._config.dbus.service)
try:
return await root.call_get_interface(ifname)
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
raise LookupError(f"interface {ifname} is not controlled by wpa_supplicant") from exc
raise LookupError(
f"interface {ifname} is not controlled by wpa_supplicant"
) from exc
raise
async def _read_interface_state_value(self, interface_path: str) -> object:
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service,
interface_path,
interface_introspection,
)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
try:
return await interface.get_state()
@ -532,7 +662,9 @@ class WpaSupplicantDbusClient:
async def _read_interface_properties(self, ifname: str) -> dict[str, object]:
interface_path = await self._get_interface_path(ifname)
return await self._read_properties(interface_path, f"{self._config.dbus.service}.Interface")
return await self._read_properties(
interface_path, f"{self._config.dbus.service}.Interface"
)
async def _read_related_object(
self,
@ -552,16 +684,24 @@ class WpaSupplicantDbusClient:
"properties": properties,
}
async def _read_properties(self, object_path: str, interface_name: str) -> dict[str, object]:
introspection = await self._bus.introspect(self._config.dbus.service, object_path)
proxy = self._bus.get_proxy_object(self._config.dbus.service, object_path, introspection)
async def _read_properties(
self, object_path: str, interface_name: str
) -> dict[str, object]:
introspection = await self._bus.introspect(
self._config.dbus.service, object_path
)
proxy = self._bus.get_proxy_object(
self._config.dbus.service, object_path, introspection
)
properties = proxy.get_interface("org.freedesktop.DBus.Properties")
try:
raw_properties = await properties.call_get_all(interface_name)
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
raise RuntimeError(f"failed to read properties for {object_path}: {exc}") from exc
raise RuntimeError(
f"failed to read properties for {object_path}: {exc}"
) from exc
raise
return _normalize_dbus_value(raw_properties)
@ -588,10 +728,16 @@ class WpaSupplicantDbusClient:
raise RuntimeError("dbus client is not connected")
self._loop.create_task(callback(event))
def _on_interface_added(self, object_path: str, properties: dict[str, object]) -> None:
def _on_interface_added(
self, object_path: str, properties: dict[str, object]
) -> None:
self._emit_event(
"InterfaceAdded",
{"object_path": object_path, "properties": properties, "selected_interface": self._config.interface},
{
"object_path": object_path,
"properties": properties,
"selected_interface": self._config.interface,
},
)
if properties.get("Ifname") == self._config.interface:
self._schedule_selected_interface_attach(object_path)
@ -627,7 +773,9 @@ class WpaSupplicantDbusClient:
},
)
def _on_interface_bss_added(self, object_path: str, properties: dict[str, object]) -> None:
def _on_interface_bss_added(
self, object_path: str, properties: dict[str, object]
) -> None:
self._emit_event(
"BSSAdded",
{
@ -648,7 +796,9 @@ class WpaSupplicantDbusClient:
},
)
def _on_interface_network_added(self, object_path: str, properties: dict[str, object]) -> None:
def _on_interface_network_added(
self, object_path: str, properties: dict[str, object]
) -> None:
self._emit_event(
"NetworkAdded",
{
@ -692,11 +842,15 @@ class WpaSupplicantDbusClient:
},
)
async def _attach_selected_interface_from_root(self, root_interface: object) -> None:
async def _attach_selected_interface_from_root(
self, root_interface: object
) -> None:
if self._bus is None:
return
try:
interface_path = await root_interface.call_get_interface(self._config.interface)
interface_path = await root_interface.call_get_interface(
self._config.interface
)
except Exception as exc: # pragma: no cover - depends on live bus state
if DBusError is not None and isinstance(exc, DBusError):
return
@ -713,9 +867,15 @@ class WpaSupplicantDbusClient:
self._selected_interface_path = interface_path
return
interface_introspection = await self._bus.introspect(self._config.dbus.service, interface_path)
interface_proxy = self._bus.get_proxy_object(self._config.dbus.service, interface_path, interface_introspection)
interface = interface_proxy.get_interface(f"{self._config.dbus.service}.Interface")
interface_introspection = await self._bus.introspect(
self._config.dbus.service, interface_path
)
interface_proxy = self._bus.get_proxy_object(
self._config.dbus.service, interface_path, interface_introspection
)
interface = interface_proxy.get_interface(
f"{self._config.dbus.service}.Interface"
)
interface.on_scan_done(self._on_interface_scan_done)
interface.on_bss_added(self._on_interface_bss_added)
@ -774,9 +934,13 @@ def _format_ssid(value: object) -> str | None:
def _byte_sequence(value: object) -> list[int] | None:
if isinstance(value, (bytes, bytearray)):
return [byte for byte in value]
if isinstance(value, list) and all(isinstance(item, int) and 0 <= item <= 255 for item in value):
if isinstance(value, list) and all(
isinstance(item, int) and 0 <= item <= 255 for item in value
):
return list(value)
if isinstance(value, tuple) and all(isinstance(item, int) and 0 <= item <= 255 for item in value):
if isinstance(value, tuple) and all(
isinstance(item, int) and 0 <= item <= 255 for item in value
):
return list(value)
return None
@ -825,7 +989,11 @@ def _parse_information_elements(value: object) -> dict[str, object] | None:
elif element_id in {1, 50}:
rates = _parse_supported_rates(data)
element["value"] = rates
key = "supported_rates_mbps" if element_id == 1 else "extended_supported_rates_mbps"
key = (
"supported_rates_mbps"
if element_id == 1
else "extended_supported_rates_mbps"
)
parsed[key] = rates["rates_mbps"]
elif element_id == 3 and data:
channel = data[0]
@ -1348,7 +1516,10 @@ def _parse_wps_information_element(data: list[int]) -> dict[str, object]:
attributes.append(_parse_wps_attribute(attr_type, attr_value))
result: dict[str, object] = {"attributes": attributes}
version = next((item.get("value") for item in attributes if item.get("name") == "Version"), None)
version = next(
(item.get("value") for item in attributes if item.get("name") == "Version"),
None,
)
if version is not None:
result["version"] = version
return result
@ -1378,7 +1549,9 @@ def _parse_wps_attribute(attr_type: int, data: list[int]) -> dict[str, object]:
elif attr_type == 0x1057:
entry["value"] = bool(data[0]) if data else None
elif attr_type in {0x1047, 0x1048}:
entry["value"] = _format_uuid_bytes(data) if len(data) == 16 else _format_hex_bytes(data)
entry["value"] = (
_format_uuid_bytes(data) if len(data) == 16 else _format_hex_bytes(data)
)
elif attr_type == 0x1049:
entry["value"] = _format_hex_bytes(data)
elif attr_type == 0x1046:
@ -1529,7 +1702,9 @@ def _format_uuid_bytes(data: list[int]) -> str:
return f"{hex_value[0:8]}-{hex_value[8:12]}-{hex_value[12:16]}-{hex_value[16:20]}-{hex_value[20:32]}"
def _parse_suite_selector(data: list[int], kind: str = "cipher") -> dict[str, object] | None:
def _parse_suite_selector(
data: list[int], kind: str = "cipher"
) -> dict[str, object] | None:
if len(data) < 4:
return None
@ -1611,7 +1786,12 @@ def _format_hex_bytes(data: list[int]) -> str:
def _read_u32_le(data: list[int], offset: int) -> int | None:
if offset + 4 > len(data):
return None
return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)
return (
data[offset]
| (data[offset + 1] << 8)
| (data[offset + 2] << 16)
| (data[offset + 3] << 24)
)
def _read_u16_be(data: list[int], offset: int) -> int | None:

View File

@ -26,7 +26,9 @@ def build_parser() -> argparse.ArgumentParser:
def main() -> int:
args = build_parser().parse_args()
config, store, _client, supervisor = build_runtime(Path(args.config), Path(args.env_file))
config, store, _client, supervisor = build_runtime(
Path(args.config), Path(args.env_file)
)
app = create_app(config, store, supervisor)
uvicorn.run(app, host=config.api.host, port=config.api.port, log_level="info")
return 0

View File

@ -21,7 +21,9 @@ def _interface_state_from_event(event: EventRecord) -> InterfaceState:
)
def build_runtime(config_path: Path, env_path: Path | None = None) -> tuple[AgentConfig, SqliteStore, WpaSupplicantDbusClient, ConnectionSupervisor]:
def build_runtime(
config_path: Path, env_path: Path | None = None
) -> tuple[AgentConfig, SqliteStore, WpaSupplicantDbusClient, ConnectionSupervisor]:
config = load_agent_config(config_path, env_path)
store = SqliteStore(config.database.path)
client = WpaSupplicantDbusClient(config)

View File

@ -53,8 +53,7 @@ class SqliteStore:
self._conn = None
def _ensure_schema(self) -> None:
self.connection.executescript(
"""
self.connection.executescript("""
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
interface TEXT NOT NULL,
@ -79,8 +78,7 @@ class SqliteStore:
refreshed_at TEXT NOT NULL,
results_json TEXT NOT NULL
);
"""
)
""")
self.connection.commit()
async def record_event(self, event: EventRecord) -> None:
@ -89,7 +87,12 @@ class SqliteStore:
INSERT INTO events(interface, event_type, payload_json, created_at)
VALUES (?, ?, ?, ?)
""",
(event.interface, event.event_type, event.payload_json, _to_timestamp(event.created_at)),
(
event.interface,
event.event_type,
event.payload_json,
_to_timestamp(event.created_at),
),
)
await self.touch_interface(
InterfaceState(
@ -123,7 +126,9 @@ class SqliteStore:
)
self.connection.commit()
async def mark_heartbeat(self, interface: str, heartbeat_at: datetime | None = None) -> None:
async def mark_heartbeat(
self, interface: str, heartbeat_at: datetime | None = None
) -> None:
heartbeat_at = heartbeat_at or datetime.now(timezone.utc)
self.connection.execute(
"""
@ -176,7 +181,8 @@ class SqliteStore:
interface=row["interface"],
event_type=row["event_type"],
payload_json=row["payload_json"],
created_at=_from_timestamp(row["created_at"]) or datetime.now(timezone.utc),
created_at=_from_timestamp(row["created_at"])
or datetime.now(timezone.utc),
)
for row in rows
]
@ -222,7 +228,11 @@ class SqliteStore:
refreshed_at = excluded.refreshed_at,
results_json = excluded.results_json
""",
(interface, _to_timestamp(refreshed_at), json.dumps(results, sort_keys=True, default=str)),
(
interface,
_to_timestamp(refreshed_at),
json.dumps(results, sort_keys=True, default=str),
),
)
self.connection.commit()

View File

@ -30,7 +30,9 @@ class SupervisorState:
class ConnectionSupervisor:
def __init__(self, config: AgentConfig, client: WpaSupplicantDbusClient, store: SqliteStore) -> None:
def __init__(
self, config: AgentConfig, client: WpaSupplicantDbusClient, store: SqliteStore
) -> None:
self._config = config
self._client = client
self._store = store
@ -84,7 +86,11 @@ class ConnectionSupervisor:
self._state.health = HealthSnapshot(
process_up=True,
dbus_up=current.dbus_up if dbus_up is None else dbus_up,
last_heartbeat_at=current.last_heartbeat_at if last_heartbeat_at is None else last_heartbeat_at,
last_heartbeat_at=(
current.last_heartbeat_at
if last_heartbeat_at is None
else last_heartbeat_at
),
ingested_records=current.ingested_records,
expired_records=current.expired_records,
message=current.message if message is None else message,
@ -97,15 +103,26 @@ class ConnectionSupervisor:
await self._client.connect()
await self._client.ping()
self._state.reconnect_delay_seconds = self._config.heartbeat.reconnect_initial_delay_seconds
self._state.reconnect_delay_seconds = (
self._config.heartbeat.reconnect_initial_delay_seconds
)
self._state.last_error = ""
self._sync_health(dbus_up=True, last_heartbeat_at=_utcnow(), message="dbus heartbeat ok")
await asyncio.wait_for(self._stop_event.wait(), timeout=self._config.heartbeat.interval_seconds)
self._sync_health(
dbus_up=True,
last_heartbeat_at=_utcnow(),
message="dbus heartbeat ok",
)
await asyncio.wait_for(
self._stop_event.wait(),
timeout=self._config.heartbeat.interval_seconds,
)
except asyncio.TimeoutError:
continue
except asyncio.CancelledError:
raise
except Exception as exc: # pragma: no cover - exercised in integration scenarios
except (
Exception
) as exc: # pragma: no cover - exercised in integration scenarios
self._state.last_error = str(exc)
self._sync_health(dbus_up=False, message=str(exc))
await self._client.disconnect()
@ -120,10 +137,14 @@ class ConnectionSupervisor:
pass
async def _retention_loop(self) -> None:
sweep_seconds = max(0.1, min(60.0, self._config.retention.record_ttl_seconds / 10.0))
sweep_seconds = max(
0.1, min(60.0, self._config.retention.record_ttl_seconds / 10.0)
)
while not self._stop_event.is_set():
try:
cutoff = datetime.now(timezone.utc) - timedelta(seconds=self._config.retention.record_ttl_seconds)
cutoff = datetime.now(timezone.utc) - timedelta(
seconds=self._config.retention.record_ttl_seconds
)
expired = await self._store.purge_expired_events(cutoff)
if expired:
self.record_expired(expired)
@ -133,10 +154,14 @@ class ConnectionSupervisor:
continue
except asyncio.CancelledError:
raise
except Exception as exc: # pragma: no cover - retention failures are handled in runtime status
except (
Exception
) as exc: # pragma: no cover - retention failures are handled in runtime status
self._state.last_error = str(exc)
self._sync_health(message=f"retention error: {exc}")
try:
await asyncio.wait_for(self._stop_event.wait(), timeout=sweep_seconds)
await asyncio.wait_for(
self._stop_event.wait(), timeout=sweep_seconds
)
except asyncio.TimeoutError:
pass

View File

@ -3,10 +3,8 @@ from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))

View File

@ -9,7 +9,15 @@ from fastapi.testclient import TestClient
from dbus_agent.api import _event_to_payload, _ttl_remaining_seconds, create_app
from dbus_agent import dbus_client
from dbus_agent.dbus_client import DbusConnectionSnapshot
from dbus_agent.models import AgentConfig, ApiSettings, DatabaseSettings, DbusSettings, EventRecord, HeartbeatSettings, InterfaceState
from dbus_agent.models import (
AgentConfig,
ApiSettings,
DatabaseSettings,
DbusSettings,
EventRecord,
HeartbeatSettings,
InterfaceState,
)
class FakeStore:
@ -41,7 +49,7 @@ class FakeStore:
"Signal": -55,
"SSID": "backup",
},
}
},
],
}
}
@ -106,7 +114,10 @@ class FakeSupervisor:
"message": "ok",
},
)()
self.connection = DbusConnectionSnapshot(connected=True, last_ping_at=datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc))
self.connection = DbusConnectionSnapshot(
connected=True,
last_ping_at=datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc),
)
self.client = self
self._stop_event = asyncio.Event()
self.scan_calls: list[str] = []
@ -223,7 +234,9 @@ def _config() -> AgentConfig:
interface="wlan0",
dbus=DbusSettings(),
database=DatabaseSettings(path=Path("/tmp/dbus-agent.sqlite3")),
api=ApiSettings(host="127.0.0.1", port=8080, api_key_header="X-Token", api_key="secret"),
api=ApiSettings(
host="127.0.0.1", port=8080, api_key_header="X-Token", api_key="secret"
),
heartbeat=HeartbeatSettings(),
)
@ -372,7 +385,9 @@ def test_api_health_state_events_and_commands() -> None:
unauthorized = client.post("/commands", json={"action": "scan"})
assert unauthorized.status_code == 401
authorized = client.post("/commands", headers={"X-Token": "secret"}, json={"action": "scan"})
authorized = client.post(
"/commands", headers={"X-Token": "secret"}, json={"action": "scan"}
)
assert authorized.status_code == 501
@ -388,7 +403,9 @@ def test_api_rejects_unconfigured_interface() -> None:
assert client.get("/interfaces/wlp2s0/current_network").status_code == 404
assert client.get("/interfaces/wlp2s0/signal_poll").status_code == 404
assert client.post("/interfaces/wlp2s0/subscribe_probe_req").status_code == 404
assert client.post("/interfaces/wlp2s0/unsubscribe_probe_req").status_code == 404
assert (
client.post("/interfaces/wlp2s0/unsubscribe_probe_req").status_code == 404
)
assert client.post("/interfaces/wlp2s0/scan").status_code == 404
assert client.post("/interfaces/wlp2s0/disconnect").status_code == 404
assert client.post("/interfaces/wlp2s0/reattach").status_code == 404
@ -396,7 +413,12 @@ def test_api_rejects_unconfigured_interface() -> None:
assert client.post("/interfaces/wlp2s0/reconnect").status_code == 404
assert client.post("/interfaces/wlp2s0/eap_logoff").status_code == 404
assert client.post("/interfaces/wlp2s0/eap_logon").status_code == 404
assert client.post("/interfaces/wlp2s0/add_network", json={"ssid": "example"}).status_code == 404
assert (
client.post(
"/interfaces/wlp2s0/add_network", json={"ssid": "example"}
).status_code
== 404
)
assert client.get("/interfaces/wlp2s0/scan_results").status_code == 404
assert client.get("/interface/wlp2s0/current_bss").status_code == 404
assert client.get("/interface/wlp2s0/current_network").status_code == 404
@ -506,7 +528,9 @@ def test_api_reattach_rejects_state_conflicts() -> None:
supervisor = FakeSupervisor()
async def conflicted_reattach(interface: str) -> None:
raise dbus_client.InterfaceConflictError("interface wlan0 cannot be reattached in its current state: Interface is not connected to any network")
raise dbus_client.InterfaceConflictError(
"interface wlan0 cannot be reattached in its current state: Interface is not connected to any network"
)
supervisor.reattach = conflicted_reattach # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
@ -650,7 +674,9 @@ def test_api_add_network_rejects_policy_denied_dbus_calls() -> None:
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/add_network", json={"ssid": "example"})
response = client.post(
"/interfaces/wlan0/add_network", json={"ssid": "example"}
)
assert response.status_code == 403
assert "policy denied" in response.json()["detail"]
@ -868,7 +894,9 @@ def test_api_add_network_rejects_invalid_args() -> None:
supervisor = FakeSupervisor()
async def invalid_add_network(interface: str, payload: dict[str, object]) -> str:
raise ValueError("invalid network configuration for wlan0: null values are not supported in D-Bus arguments")
raise ValueError(
"invalid network configuration for wlan0: null values are not supported in D-Bus arguments"
)
supervisor.add_network = invalid_add_network # type: ignore[assignment]
app = create_app(_config(), store, supervisor)
@ -890,6 +918,8 @@ def test_api_add_network_propagates_dbus_errors() -> None:
app = create_app(_config(), store, supervisor)
with TestClient(app) as client:
response = client.post("/interfaces/wlan0/add_network", json={"ssid": "example"})
response = client.post(
"/interfaces/wlan0/add_network", json={"ssid": "example"}
)
assert response.status_code == 503
assert "failed to add network" in response.json()["detail"]

View File

@ -56,7 +56,9 @@ def test_api_client_uses_mock_transport_and_api_key_for_commands() -> None:
client,
)
result = _run_command(argparse.Namespace(command="command", payload='{"action":"scan"}'), api)
result = _run_command(
argparse.Namespace(command="command", payload='{"action":"scan"}'), api
)
assert result.status_code == 200
assert seen["path"] == "/commands"
@ -110,7 +112,11 @@ def test_cli_state_json_output() -> None:
"health": httpx.Response(200, json={"ok": True}),
"state:wlan0": httpx.Response(
200,
json={"interface": "wlan0", "status": "healthy", "details": {"ssid": "example"}},
json={
"interface": "wlan0",
"status": "healthy",
"details": {"ssid": "example"},
},
),
"events:wlan0:100": httpx.Response(404, json={"detail": "not used"}),
"scan_results:wlan0": httpx.Response(404, json={"detail": "not used"}),
@ -265,7 +271,11 @@ def test_cli_error_scenarios() -> None:
transport_exit = run(
["health"],
client_factory=lambda settings: _RaisingClient(httpx.ConnectError("down", request=httpx.Request("GET", "http://test/health"))),
client_factory=lambda settings: _RaisingClient(
httpx.ConnectError(
"down", request=httpx.Request("GET", "http://test/health")
)
),
stdout=stdout,
stderr=stderr,
)
@ -300,7 +310,9 @@ def test_cli_error_scenarios() -> None:
"health": httpx.Response(200, json={"ok": True}),
"state:missing": httpx.Response(404, json={"detail": "not found"}),
"events:missing:100": httpx.Response(404, json={"detail": "not used"}),
"scan_results:missing": httpx.Response(404, json={"detail": "not used"}),
"scan_results:missing": httpx.Response(
404, json={"detail": "not used"}
),
"command": httpx.Response(501, json={"detail": {"message": "stub"}}),
}
),

View File

@ -21,8 +21,7 @@ event_filter:
allowed_event_types:
- InterfaceAdded
- InterfaceRemoved
""".strip()
+ "\n",
""".strip() + "\n",
encoding="utf-8",
)
@ -36,8 +35,7 @@ DBUS_AGENT_API_PORT=9090
DBUS_AGENT_DATABASE_PATH=/tmp/dbus-agent.sqlite3
DBUS_AGENT_RECORD_TTL_SECONDS=7200
DBUS_AGENT_EVENT_FILTER_ALLOWED_EVENT_TYPES=ScanDone, PropertiesChanged
""".strip()
+ "\n",
""".strip() + "\n",
encoding="utf-8",
)
@ -58,15 +56,16 @@ DBUS_AGENT_EVENT_FILTER_ALLOWED_EVENT_TYPES=ScanDone, PropertiesChanged
assert config.event_filter.allowed_event_types == ("ScanDone", "PropertiesChanged")
def test_load_agent_config_defaults_event_filter_to_all_events(tmp_path: Path, monkeypatch) -> None:
def test_load_agent_config_defaults_event_filter_to_all_events(
tmp_path: Path, monkeypatch
) -> None:
config_path = tmp_path / "config.yaml"
config_path.write_text(
"""
interface: wlan0
database:
path: /var/lib/dbus-agent/dbus-agent.sqlite3
""".strip()
+ "\n",
""".strip() + "\n",
encoding="utf-8",
)

View File

@ -124,8 +124,12 @@ class FakeInterfaceProperties:
"/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1",
]
),
"CurrentBSS": SimpleNamespace(value="/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/0"),
"CurrentNetwork": SimpleNamespace(value="/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0"),
"CurrentBSS": SimpleNamespace(
value="/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/0"
),
"CurrentNetwork": SimpleNamespace(
value="/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0"
),
"Scanning": SimpleNamespace(value=False),
"State": SimpleNamespace(value="completed"),
}
@ -150,7 +154,10 @@ def _fake_ie_blob() -> list[int]:
(3, "95"),
(11, "040000127a"),
(45, "ef0117ffff000000000000000000000000000000001804870900"),
(48, "0100000fac040100000fac040100000fac0200002d1aef0117ffff000000000000000000000000000000001804"),
(
48,
"0100000fac040100000fac040100000fac0200002d1aef0117ffff000000000000000000000000000000001804",
),
(61, "95050400000000000000000000000000000000000000"),
(127, "0000000000000040"),
(191, "b179c933faff0c03faff0c03"),
@ -180,7 +187,9 @@ class FakeProperties:
class FakeProxy:
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
self._object_path = object_path
self._root_interface = root_interface
self._bus = bus
@ -191,16 +200,33 @@ class FakeProxy:
self._network_properties = FakeNetworkProperties()
def get_interface(self, name: str): # type: ignore[no-untyped-def]
if self._object_path == "/fi/w1/wpa_supplicant1" and name == "fi.w1.wpa_supplicant1":
if (
self._object_path == "/fi/w1/wpa_supplicant1"
and name == "fi.w1.wpa_supplicant1"
):
return self._root_interface
if self._object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0" and name == "fi.w1.wpa_supplicant1.Interface":
if (
self._object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0"
and name == "fi.w1.wpa_supplicant1.Interface"
):
self._bus.selected_interface = self._interface
return self._interface
if self._object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0" and name == "org.freedesktop.DBus.Properties":
if (
self._object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0"
and name == "org.freedesktop.DBus.Properties"
):
return self._interface_properties
if self._object_path.startswith("/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/") and name == "org.freedesktop.DBus.Properties":
if (
self._object_path.startswith(
"/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/"
)
and name == "org.freedesktop.DBus.Properties"
):
return self._bss_properties
if self._object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0" and name == "org.freedesktop.DBus.Properties":
if (
self._object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0"
and name == "org.freedesktop.DBus.Properties"
):
return self._network_properties
if name == "org.freedesktop.DBus.Properties":
return self._properties
@ -223,7 +249,9 @@ class FakeBus:
self.introspect_calls.append((service, object_path))
return object()
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return FakeProxy(object_path, self.root_interface, self)
def disconnect(self) -> None:
@ -233,7 +261,9 @@ class FakeBus:
def _config() -> AgentConfig:
return AgentConfig(
interface="wlp3s0",
dbus=DbusSettings(service="fi.w1.wpa_supplicant1", object_path="/fi/w1/wpa_supplicant1"),
dbus=DbusSettings(
service="fi.w1.wpa_supplicant1", object_path="/fi/w1/wpa_supplicant1"
),
database=DatabaseSettings(path=Path("/tmp/dbus-agent.sqlite3")),
api=ApiSettings(),
)
@ -276,12 +306,18 @@ def test_dbus_client_uses_wpa_supplicant_signals(monkeypatch) -> None:
assert selected.network_selected_handler is not None
assert selected.properties_changed_handler is not None
root.interface_added_handler("/fi/w1/wpa_supplicant1/Interfaces/1", {"ssid": "example"})
root.interface_added_handler(
"/fi/w1/wpa_supplicant1/Interfaces/1", {"ssid": "example"}
)
root.interface_removed_handler("/fi/w1/wpa_supplicant1/Interfaces/1")
root.properties_changed_handler({"State": "completed"})
selected.scan_done_handler(True)
selected.bss_added_handler("/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1", {"Signal": -31})
selected.network_selected_handler("/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0")
selected.bss_added_handler(
"/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1", {"Signal": -31}
)
selected.network_selected_handler(
"/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0"
)
selected.properties_changed_handler({"State": "scanning"})
await asyncio.sleep(0)
@ -301,14 +337,38 @@ def test_dbus_client_uses_wpa_supplicant_signals(monkeypatch) -> None:
"NetworkSelected",
"PropertiesChanged",
]
assert events[0].payload_json == '{"object_path": "/fi/w1/wpa_supplicant1", "selected_interface": "wlp3s0", "service": "fi.w1.wpa_supplicant1"}'
assert events[1].payload_json == '{"object_path": "/fi/w1/wpa_supplicant1/Interfaces/1", "properties": {"ssid": "example"}, "selected_interface": "wlp3s0"}'
assert events[2].payload_json == '{"object_path": "/fi/w1/wpa_supplicant1/Interfaces/1", "selected_interface": "wlp3s0"}'
assert events[3].payload_json == '{"changed_properties": {"State": "completed"}, "selected_interface": "wlp3s0"}'
assert events[4].payload_json == '{"interface_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0", "selected_interface": "wlp3s0", "success": true}'
assert events[5].payload_json == '{"interface_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0", "object_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1", "properties": {"Signal": -31}, "selected_interface": "wlp3s0"}'
assert events[6].payload_json == '{"interface_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0", "object_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0", "selected_interface": "wlp3s0"}'
assert events[7].payload_json == '{"changed_properties": {"State": "scanning"}, "interface_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0", "selected_interface": "wlp3s0"}'
assert (
events[0].payload_json
== '{"object_path": "/fi/w1/wpa_supplicant1", "selected_interface": "wlp3s0", "service": "fi.w1.wpa_supplicant1"}'
)
assert (
events[1].payload_json
== '{"object_path": "/fi/w1/wpa_supplicant1/Interfaces/1", "properties": {"ssid": "example"}, "selected_interface": "wlp3s0"}'
)
assert (
events[2].payload_json
== '{"object_path": "/fi/w1/wpa_supplicant1/Interfaces/1", "selected_interface": "wlp3s0"}'
)
assert (
events[3].payload_json
== '{"changed_properties": {"State": "completed"}, "selected_interface": "wlp3s0"}'
)
assert (
events[4].payload_json
== '{"interface_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0", "selected_interface": "wlp3s0", "success": true}'
)
assert (
events[5].payload_json
== '{"interface_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0", "object_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1", "properties": {"Signal": -31}, "selected_interface": "wlp3s0"}'
)
assert (
events[6].payload_json
== '{"interface_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0", "object_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0", "selected_interface": "wlp3s0"}'
)
assert (
events[7].payload_json
== '{"changed_properties": {"State": "scanning"}, "interface_path": "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0", "selected_interface": "wlp3s0"}'
)
assert client.snapshot.connected is True
asyncio.run(scenario())
@ -393,7 +453,16 @@ def test_dbus_client_reads_current_bss_and_network(monkeypatch) -> None:
assert element_127["value"]["bytes"] == [0, 0, 0, 0, 0, 0, 0, 64]
element_191 = next(item for item in ies["elements"] if item["id"] == 191)
assert element_191["value"]["supported_mcs_set_raw"] == [250, 255, 12, 3, 250, 255, 12, 3]
assert element_191["value"]["supported_mcs_set_raw"] == [
250,
255,
12,
3,
250,
255,
12,
3,
]
element_192 = next(item for item in ies["elements"] if item["id"] == 192)
assert element_192["value"]["channel_width"] == 1
@ -414,17 +483,26 @@ def test_dbus_client_reads_current_bss_and_network(monkeypatch) -> None:
assert wmm["ac_parameters"][3]["txop_limit_raw"] == 47
assert wmm["ac_parameters"][3]["txop_limit_us"] == 1504
assert current_network is not None
assert current_network["path"] == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0"
assert (
current_network["path"]
== "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0"
)
assert current_network["properties"]["Enabled"] is True
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/0"),
(
"fi.w1.wpa_supplicant1",
"/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/0",
),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0"),
(
"fi.w1.wpa_supplicant1",
"/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/Networks/0",
),
]
asyncio.run(scenario())
@ -448,17 +526,27 @@ def test_dbus_client_reads_scan_results(monkeypatch) -> None:
scan_results = await client.read_scan_results("wlp3s0")
assert len(scan_results) == 2
assert scan_results[0]["path"] == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/0"
assert (
scan_results[0]["path"] == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/0"
)
assert scan_results[0]["properties"]["SSID"] == "example"
assert scan_results[1]["path"] == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1"
assert (
scan_results[1]["path"] == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1"
)
assert scan_results[1]["properties"]["Signal"] == -42
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/0"),
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1"),
(
"fi.w1.wpa_supplicant1",
"/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/0",
),
(
"fi.w1.wpa_supplicant1",
"/fi/w1/wpa_supplicant1/Interfaces/wlp3s0/BSSs/1",
),
]
asyncio.run(scenario())
@ -685,7 +773,9 @@ def test_dbus_client_eap_logons_selected_interface(monkeypatch) -> None:
asyncio.run(scenario())
def test_dbus_client_subscribes_probe_requests_for_selected_interface(monkeypatch) -> None:
def test_dbus_client_subscribes_probe_requests_for_selected_interface(
monkeypatch,
) -> None:
created: dict[str, FakeBus] = {}
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -716,7 +806,9 @@ def test_dbus_client_subscribes_probe_requests_for_selected_interface(monkeypatc
asyncio.run(scenario())
def test_dbus_client_unsubscribes_probe_requests_for_selected_interface(monkeypatch) -> None:
def test_dbus_client_unsubscribes_probe_requests_for_selected_interface(
monkeypatch,
) -> None:
created: dict[str, FakeBus] = {}
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -791,16 +883,22 @@ def test_dbus_client_reports_interface_disabled_for_reassociate(monkeypatch) ->
class DisabledInterface(FakeInterface):
async def call_reassociate(self) -> None:
raise InterfaceDisabledError("fi.w1.wpa_supplicant1.InterfaceDisabled", "Interface is disabled")
raise InterfaceDisabledError(
"fi.w1.wpa_supplicant1.InterfaceDisabled", "Interface is disabled"
)
class DisabledProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DisabledInterface()
class DisabledBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DisabledProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -844,16 +942,22 @@ def test_dbus_client_reports_access_denied_for_signal_poll(monkeypatch) -> None:
class DeniedInterface(FakeInterface):
async def call_signal_poll(self) -> dict[str, object]:
raise AccessDeniedError("org.freedesktop.DBus.Error.AccessDenied", "Rejected send message")
raise AccessDeniedError(
"org.freedesktop.DBus.Error.AccessDenied", "Rejected send message"
)
class DeniedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DeniedInterface()
class DeniedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DeniedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -897,16 +1001,22 @@ def test_dbus_client_reports_access_denied_for_subscribe_probe_req(monkeypatch)
class DeniedInterface(FakeInterface):
async def call_subscribe_probe_req(self) -> None:
raise AccessDeniedError("org.freedesktop.DBus.Error.AccessDenied", "Rejected send message")
raise AccessDeniedError(
"org.freedesktop.DBus.Error.AccessDenied", "Rejected send message"
)
class DeniedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DeniedInterface()
class DeniedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DeniedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -927,7 +1037,9 @@ def test_dbus_client_reports_access_denied_for_subscribe_probe_req(monkeypatch)
except PermissionError as exc:
assert "policy denied" in str(exc)
else: # pragma: no cover - defensive assertion
raise AssertionError("subscribe_probe_req should have been denied by policy")
raise AssertionError(
"subscribe_probe_req should have been denied by policy"
)
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
@ -939,7 +1051,9 @@ def test_dbus_client_reports_access_denied_for_subscribe_probe_req(monkeypatch)
asyncio.run(scenario())
def test_dbus_client_reports_access_denied_for_unsubscribe_probe_req(monkeypatch) -> None:
def test_dbus_client_reports_access_denied_for_unsubscribe_probe_req(
monkeypatch,
) -> None:
created: dict[str, FakeBus] = {}
class AccessDeniedError(Exception):
@ -950,16 +1064,22 @@ def test_dbus_client_reports_access_denied_for_unsubscribe_probe_req(monkeypatch
class DeniedInterface(FakeInterface):
async def call_unsubscribe_probe_req(self) -> None:
raise AccessDeniedError("org.freedesktop.DBus.Error.AccessDenied", "Rejected send message")
raise AccessDeniedError(
"org.freedesktop.DBus.Error.AccessDenied", "Rejected send message"
)
class DeniedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DeniedInterface()
class DeniedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DeniedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -980,7 +1100,9 @@ def test_dbus_client_reports_access_denied_for_unsubscribe_probe_req(monkeypatch
except PermissionError as exc:
assert "policy denied" in str(exc)
else: # pragma: no cover - defensive assertion
raise AssertionError("unsubscribe_probe_req should have been denied by policy")
raise AssertionError(
"unsubscribe_probe_req should have been denied by policy"
)
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
@ -992,7 +1114,9 @@ def test_dbus_client_reports_access_denied_for_unsubscribe_probe_req(monkeypatch
asyncio.run(scenario())
def test_dbus_client_reports_runtime_error_for_unsubscribe_probe_req(monkeypatch) -> None:
def test_dbus_client_reports_runtime_error_for_unsubscribe_probe_req(
monkeypatch,
) -> None:
created: dict[str, FakeBus] = {}
class BrokenInterface(FakeInterface):
@ -1000,13 +1124,17 @@ def test_dbus_client_reports_runtime_error_for_unsubscribe_probe_req(monkeypatch
raise RuntimeError("boom")
class BrokenProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = BrokenInterface()
class BrokenBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return BrokenProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -1026,7 +1154,9 @@ def test_dbus_client_reports_runtime_error_for_unsubscribe_probe_req(monkeypatch
except RuntimeError as exc:
assert "boom" in str(exc)
else: # pragma: no cover - defensive assertion
raise AssertionError("unsubscribe_probe_req should have raised a runtime error")
raise AssertionError(
"unsubscribe_probe_req should have raised a runtime error"
)
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
@ -1046,13 +1176,17 @@ def test_dbus_client_reports_runtime_error_for_subscribe_probe_req(monkeypatch)
raise RuntimeError("boom")
class BrokenProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = BrokenInterface()
class BrokenBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return BrokenProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -1072,7 +1206,9 @@ def test_dbus_client_reports_runtime_error_for_subscribe_probe_req(monkeypatch)
except RuntimeError as exc:
assert "boom" in str(exc)
else: # pragma: no cover - defensive assertion
raise AssertionError("subscribe_probe_req should have raised a runtime error")
raise AssertionError(
"subscribe_probe_req should have raised a runtime error"
)
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
@ -1095,16 +1231,23 @@ def test_dbus_client_reports_not_connected_for_reconnect(monkeypatch) -> None:
class DisconnectedInterface(FakeInterface):
async def call_reconnect(self) -> None:
raise NotConnectedError("fi.w1.wpa_supplicant1.NotConnected", "Interface is not connected to any network")
raise NotConnectedError(
"fi.w1.wpa_supplicant1.NotConnected",
"Interface is not connected to any network",
)
class DisconnectedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DisconnectedInterface()
class DisconnectedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DisconnectedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -1125,7 +1268,9 @@ def test_dbus_client_reports_not_connected_for_reconnect(monkeypatch) -> None:
except dbus_client.InterfaceConflictError as exc:
assert "cannot be reconnected" in str(exc)
else: # pragma: no cover - defensive assertion
raise AssertionError("reconnect should have been rejected when disconnected")
raise AssertionError(
"reconnect should have been rejected when disconnected"
)
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
@ -1148,16 +1293,23 @@ def test_dbus_client_reports_not_connected_for_signal_poll(monkeypatch) -> None:
class DisconnectedInterface(FakeInterface):
async def call_signal_poll(self) -> dict[str, object]:
raise NotConnectedError("fi.w1.wpa_supplicant1.NotConnected", "Interface is not connected to any network")
raise NotConnectedError(
"fi.w1.wpa_supplicant1.NotConnected",
"Interface is not connected to any network",
)
class DisconnectedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DisconnectedInterface()
class DisconnectedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DisconnectedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -1178,7 +1330,9 @@ def test_dbus_client_reports_not_connected_for_signal_poll(monkeypatch) -> None:
except dbus_client.InterfaceConflictError as exc:
assert "cannot be signal-polled" in str(exc)
else: # pragma: no cover - defensive assertion
raise AssertionError("signal_poll should have been rejected when disconnected")
raise AssertionError(
"signal_poll should have been rejected when disconnected"
)
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
@ -1201,16 +1355,23 @@ def test_dbus_client_reports_not_connected_for_eap_logoff(monkeypatch) -> None:
class DisconnectedInterface(FakeInterface):
async def call_eap_logoff(self) -> None:
raise NotConnectedError("fi.w1.wpa_supplicant1.NotConnected", "Interface is not connected to any network")
raise NotConnectedError(
"fi.w1.wpa_supplicant1.NotConnected",
"Interface is not connected to any network",
)
class DisconnectedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DisconnectedInterface()
class DisconnectedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DisconnectedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -1231,7 +1392,9 @@ def test_dbus_client_reports_not_connected_for_eap_logoff(monkeypatch) -> None:
except dbus_client.InterfaceConflictError as exc:
assert "cannot be logged off" in str(exc)
else: # pragma: no cover - defensive assertion
raise AssertionError("eap_logoff should have been rejected when disconnected")
raise AssertionError(
"eap_logoff should have been rejected when disconnected"
)
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
@ -1254,16 +1417,23 @@ def test_dbus_client_reports_not_connected_for_eap_logon(monkeypatch) -> None:
class DisconnectedInterface(FakeInterface):
async def call_eap_logon(self) -> None:
raise NotConnectedError("fi.w1.wpa_supplicant1.NotConnected", "Interface is not connected to any network")
raise NotConnectedError(
"fi.w1.wpa_supplicant1.NotConnected",
"Interface is not connected to any network",
)
class DisconnectedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DisconnectedInterface()
class DisconnectedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DisconnectedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -1284,7 +1454,9 @@ def test_dbus_client_reports_not_connected_for_eap_logon(monkeypatch) -> None:
except dbus_client.InterfaceConflictError as exc:
assert "cannot be logged on" in str(exc)
else: # pragma: no cover - defensive assertion
raise AssertionError("eap_logon should have been rejected when disconnected")
raise AssertionError(
"eap_logon should have been rejected when disconnected"
)
assert created["bus"].introspect_calls == [
("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1"),
@ -1390,16 +1562,22 @@ def test_dbus_client_reports_policy_denied_scan(monkeypatch) -> None:
class DeniedInterface(FakeInterface):
async def call_scan(self, options: dict[str, object]) -> None:
raise AccessDeniedError("org.freedesktop.DBus.Error.AccessDenied", "Rejected send message")
raise AccessDeniedError(
"org.freedesktop.DBus.Error.AccessDenied", "Rejected send message"
)
class DeniedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DeniedInterface()
class DeniedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DeniedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -1443,16 +1621,22 @@ def test_dbus_client_reports_policy_denied_disconnect(monkeypatch) -> None:
class DeniedInterface(FakeInterface):
async def call_disconnect(self) -> None:
raise AccessDeniedError("org.freedesktop.DBus.Error.AccessDenied", "Rejected send message")
raise AccessDeniedError(
"org.freedesktop.DBus.Error.AccessDenied", "Rejected send message"
)
class DeniedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DeniedInterface()
class DeniedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DeniedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]
@ -1496,16 +1680,23 @@ def test_dbus_client_reports_not_connected_for_reattach(monkeypatch) -> None:
class DisconnectedInterface(FakeInterface):
async def call_reattach(self) -> None:
raise NotConnectedError("fi.w1.wpa_supplicant1.NotConnected", "Interface is not connected to any network")
raise NotConnectedError(
"fi.w1.wpa_supplicant1.NotConnected",
"Interface is not connected to any network",
)
class DisconnectedProxy(FakeProxy):
def __init__(self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus") -> None:
def __init__(
self, object_path: str, root_interface: FakeRootInterface, bus: "FakeBus"
) -> None:
super().__init__(object_path, root_interface, bus)
if object_path == "/fi/w1/wpa_supplicant1/Interfaces/wlp3s0":
self._interface = DisconnectedInterface()
class DisconnectedBus(FakeBus):
def get_proxy_object(self, service: str, object_path: str, introspection: object) -> FakeProxy:
def get_proxy_object(
self, service: str, object_path: str, introspection: object
) -> FakeProxy:
return DisconnectedProxy(object_path, self.root_interface, self)
def fake_message_bus(*, bus_type): # type: ignore[no-untyped-def]

View File

@ -20,7 +20,9 @@ def test_main_module_invokes_entrypoint(monkeypatch) -> None:
"build_runtime",
lambda config_path, env_path: (fake_config, None, None, _FakeSupervisor()),
)
monkeypatch.setattr(dbus_agent.api, "create_app", lambda config, store, supervisor: object())
monkeypatch.setattr(
dbus_agent.api, "create_app", lambda config, store, supervisor: object()
)
monkeypatch.setattr(uvicorn, "run", lambda app, host, port, log_level: None)
monkeypatch.setattr(sys, "argv", ["dbus-agent"])

View File

@ -44,7 +44,12 @@ class FakeClient:
async def read_scan_results(self, interface: str) -> list[dict[str, object]]: # type: ignore[no-untyped-def]
self.scan_results_requested.append(interface)
return [{"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0", "properties": {"SSID": "example"}}]
return [
{
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0",
"properties": {"SSID": "example"},
}
]
def test_build_runtime_wires_ingest_callback(tmp_path: Path, monkeypatch) -> None:
@ -54,8 +59,7 @@ def test_build_runtime_wires_ingest_callback(tmp_path: Path, monkeypatch) -> Non
interface: wlan0
database:
path: /tmp/dbus-agent.sqlite3
""".strip()
+ "\n",
""".strip() + "\n",
encoding="utf-8",
)
@ -79,13 +83,20 @@ database:
asyncio.run(client.callbacks[0](event))
assert len(store.recorded) == 1
assert store.scan_results == [{"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0", "properties": {"SSID": "example"}}]
assert store.scan_results == [
{
"path": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0",
"properties": {"SSID": "example"},
}
]
assert client.scan_results_requested == ["wlan0"]
assert supervisor.health.ingested_records == 1
assert config.retention.record_ttl_seconds == 7200.0
def test_build_runtime_filters_event_cache_but_keeps_scan_done_refresh(tmp_path: Path, monkeypatch) -> None:
def test_build_runtime_filters_event_cache_but_keeps_scan_done_refresh(
tmp_path: Path, monkeypatch
) -> None:
config_path = tmp_path / "config.yaml"
config_path.write_text(
"""
@ -95,8 +106,7 @@ database:
event_filter:
allowed_event_types:
- PropertiesChanged
""".strip()
+ "\n",
""".strip() + "\n",
encoding="utf-8",
)
@ -135,4 +145,7 @@ event_filter:
assert client.scan_results_requested == ["wlan0"]
assert supervisor.health.ingested_records == 1
assert config.event_filter.allowed_event_types == ("PropertiesChanged",)
assert any(state.last_event_at == datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc) for state in store.touched)
assert any(
state.last_event_at == datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc)
for state in store.touched
)

View File

@ -20,14 +20,18 @@ def test_sqlite_store_roundtrip(tmp_path: Path) -> None:
created_at=datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc),
)
await store.record_event(event)
await store.mark_heartbeat("wlan0", datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc))
await store.mark_heartbeat(
"wlan0", datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc)
)
state = await store.get_state("wlan0")
assert state is not None
assert state.interface == "wlan0"
assert state.status == "healthy"
assert state.last_event_at == datetime(2026, 3, 31, 8, 0, tzinfo=timezone.utc)
assert state.last_heartbeat_at == datetime(2026, 3, 31, 8, 1, tzinfo=timezone.utc)
assert state.last_heartbeat_at == datetime(
2026, 3, 31, 8, 1, tzinfo=timezone.utc
)
events = await store.list_events("wlan0", limit=10)
assert len(events) == 1
@ -46,14 +50,18 @@ def test_sqlite_store_roundtrip(tmp_path: Path) -> None:
cached = await store.get_scan_results("wlan0")
assert cached is not None
assert cached["interface"] == "wlan0"
assert cached["refreshed_at"] == datetime(2026, 3, 31, 8, 2, tzinfo=timezone.utc)
assert cached["refreshed_at"] == datetime(
2026, 3, 31, 8, 2, tzinfo=timezone.utc
)
assert cached["results"][0]["properties"]["SSID"] == "example"
await store.close()
asyncio.run(scenario())
def test_sqlite_store_purges_expired_events_without_touching_state(tmp_path: Path) -> None:
def test_sqlite_store_purges_expired_events_without_touching_state(
tmp_path: Path,
) -> None:
async def scenario() -> None:
store = SqliteStore(tmp_path / "db.sqlite3")
await store.open()
@ -85,7 +93,9 @@ def test_sqlite_store_purges_expired_events_without_touching_state(tmp_path: Pat
)
)
expired = await store.purge_expired_events(datetime(2026, 3, 31, 7, 30, tzinfo=timezone.utc))
expired = await store.purge_expired_events(
datetime(2026, 3, 31, 7, 30, tzinfo=timezone.utc)
)
assert expired == 1
events = await store.list_events("wlan0", limit=10)
@ -95,7 +105,9 @@ def test_sqlite_store_purges_expired_events_without_touching_state(tmp_path: Pat
state = await store.get_state("wlan0")
assert state is not None
assert state.status == "active"
assert state.last_heartbeat_at == datetime(2026, 3, 31, 7, 5, tzinfo=timezone.utc)
assert state.last_heartbeat_at == datetime(
2026, 3, 31, 7, 5, tzinfo=timezone.utc
)
await store.close()

View File

@ -5,7 +5,14 @@ from datetime import datetime, timezone
from pathlib import Path
from dbus_agent.dbus_client import DbusConnectionSnapshot
from dbus_agent.models import AgentConfig, ApiSettings, DatabaseSettings, DbusSettings, HeartbeatSettings, RetentionSettings
from dbus_agent.models import (
AgentConfig,
ApiSettings,
DatabaseSettings,
DbusSettings,
HeartbeatSettings,
RetentionSettings,
)
from dbus_agent.supervisor import ConnectionSupervisor
@ -19,7 +26,9 @@ class FakeClient:
async def connect(self) -> None:
self.connect_calls += 1
self.snapshot = DbusConnectionSnapshot(connected=True, last_ping_at=datetime.now(timezone.utc))
self.snapshot = DbusConnectionSnapshot(
connected=True, last_ping_at=datetime.now(timezone.utc)
)
async def ping(self) -> None:
self.ping_calls += 1
@ -27,11 +36,15 @@ class FakeClient:
self._failed_once = True
self.snapshot = DbusConnectionSnapshot(connected=False, last_error="boom")
raise RuntimeError("boom")
self.snapshot = DbusConnectionSnapshot(connected=True, last_ping_at=datetime.now(timezone.utc))
self.snapshot = DbusConnectionSnapshot(
connected=True, last_ping_at=datetime.now(timezone.utc)
)
async def disconnect(self) -> None:
self.disconnect_calls += 1
self.snapshot = DbusConnectionSnapshot(connected=False, last_error=self.snapshot.last_error)
self.snapshot = DbusConnectionSnapshot(
connected=False, last_error=self.snapshot.last_error
)
class FakeStore:

View File

@ -3,4 +3,10 @@
from .config import AppConfig, ConfigError
from .models import JournalEvent, MessageAclRule, ServiceStatus
__all__ = ["AppConfig", "ConfigError", "JournalEvent", "MessageAclRule", "ServiceStatus"]
__all__ = [
"AppConfig",
"ConfigError",
"JournalEvent",
"MessageAclRule",
"ServiceStatus",
]

View File

@ -61,7 +61,9 @@ def create_app(core: ApplicationCore, manage_lifecycle: bool = False) -> FastAPI
if manage_lifecycle:
core.stop()
app = FastAPI(title="journal-event-collector", lifespan=lifespan if manage_lifecycle else None)
app = FastAPI(
title="journal-event-collector", lifespan=lifespan if manage_lifecycle else None
)
@app.get("/health")
def health() -> dict[str, str]:
@ -73,13 +75,17 @@ def create_app(core: ApplicationCore, manage_lifecycle: bool = False) -> FastAPI
@app.get("/events", response_model=list[EventResponse])
def events() -> list[EventResponse]:
return [EventResponse.model_validate(event.to_dict()) for event in core.events()]
return [
EventResponse.model_validate(event.to_dict()) for event in core.events()
]
@app.get("/state", response_model=StateSnapshotResponse)
def state() -> StateSnapshotResponse:
snapshot = core.persisted_snapshot()
if snapshot is None:
raise HTTPException(status_code=404, detail="state snapshot is not available")
raise HTTPException(
status_code=404, detail="state snapshot is not available"
)
return StateSnapshotResponse(
status=snapshot.status,
events=[EventResponse.model_validate(event) for event in snapshot.events],

View File

@ -1,9 +1,9 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from datetime import datetime, timedelta
from threading import RLock
from typing import Callable, Iterable
from typing import Callable
from .models import JournalEvent, utc_now
@ -33,7 +33,11 @@ class EventCache:
current = now()
removed = 0
with self._lock:
expired_ids = [event_id for event_id, record in self._records.items() if record.expires_at <= current]
expired_ids = [
event_id
for event_id, record in self._records.items()
if record.expires_at <= current
]
for event_id in expired_ids:
removed += 1
self._records.pop(event_id, None)

View File

@ -13,7 +13,6 @@ from .runtime import ApplicationRuntime
from .service import ApplicationCore
from .state import StateStore
app = typer.Typer(help="Journal event collector")
DEFAULT_CONFIG_PATH = "/etc/journal-event-collector/config.toml"

View File

@ -93,7 +93,9 @@ def _parse_message_acl_key_value_rule(tokens: list[str], index: int) -> MessageA
cache_policy = fields.get("cache")
send_policy = fields.get("send")
mark = fields.get("mark")
return _build_message_acl_rule(process_name, message_regex, cache_policy, send_policy, mark, index)
return _build_message_acl_rule(
process_name, message_regex, cache_policy, send_policy, mark, index
)
def _parse_message_acl_positional_rule(tokens: list[str], index: int) -> MessageAclRule:
@ -119,14 +121,18 @@ def _parse_message_acl_positional_rule(tokens: list[str], index: int) -> Message
if position >= len(tokens):
raise ConfigError(f"message_acl[{index}].process is missing a value")
if process_name is not None:
raise ConfigError(f"message_acl[{index}] contains duplicate process field")
raise ConfigError(
f"message_acl[{index}] contains duplicate process field"
)
process_name = tokens[position]
elif key in {"regexp", "message_regex"}:
position += 1
if position >= len(tokens):
raise ConfigError(f"message_acl[{index}].regexp is missing a value")
if message_regex is not None:
raise ConfigError(f"message_acl[{index}] contains duplicate regexp field")
raise ConfigError(
f"message_acl[{index}] contains duplicate regexp field"
)
message_regex = tokens[position]
elif key == "send":
position += 1
@ -143,13 +149,19 @@ def _parse_message_acl_positional_rule(tokens: list[str], index: int) -> Message
raise ConfigError(f"message_acl[{index}] contains duplicate mark field")
mark = tokens[position]
else:
raise ConfigError(f"message_acl[{index}] contains unsupported token: {tokens[position]}")
raise ConfigError(
f"message_acl[{index}] contains unsupported token: {tokens[position]}"
)
position += 1
if cache_policy == "drop" and (send_policy is not None or mark is not None):
raise ConfigError(f"message_acl[{index}] must not define send or mark when cache='drop'")
raise ConfigError(
f"message_acl[{index}] must not define send or mark when cache='drop'"
)
return _build_message_acl_rule(process_name, message_regex, cache_policy, send_policy, mark, index)
return _build_message_acl_rule(
process_name, message_regex, cache_policy, send_policy, mark, index
)
def _build_message_acl_rule(
@ -161,22 +173,32 @@ def _build_message_acl_rule(
index: int,
) -> MessageAclRule:
if not isinstance(process_name, str) or not process_name.strip():
raise ConfigError(f"message_acl[{index}].process_name must be a non-empty string")
raise ConfigError(
f"message_acl[{index}].process_name must be a non-empty string"
)
if not isinstance(message_regex, str) or not message_regex.strip():
raise ConfigError(f"message_acl[{index}].message_regex must be a non-empty string")
raise ConfigError(
f"message_acl[{index}].message_regex must be a non-empty string"
)
if not isinstance(cache_policy, str) or not cache_policy.strip():
raise ConfigError(f"message_acl[{index}].cache must be a non-empty string")
cache_value = cache_policy.strip().casefold()
if cache_value not in {"cache", "drop"}:
raise ConfigError(f"message_acl[{index}].cache must be either 'cache' or 'drop'")
raise ConfigError(
f"message_acl[{index}].cache must be either 'cache' or 'drop'"
)
try:
if cache_value == "drop":
if send_policy is not None:
raise ConfigError(f"message_acl[{index}].send is not allowed when cache='drop'")
raise ConfigError(
f"message_acl[{index}].send is not allowed when cache='drop'"
)
if mark is not None:
raise ConfigError(f"message_acl[{index}].mark is not allowed when cache='drop'")
raise ConfigError(
f"message_acl[{index}].mark is not allowed when cache='drop'"
)
return MessageAclRule(
process_name=process_name.strip(),
message_regex=message_regex.strip(),
@ -204,10 +226,17 @@ def _build_message_acl_rule(
) from exc
except ValueError as exc:
message = str(exc)
if "mark must contain only ASCII letters, digits, underscore, and hyphen" in message:
raise ConfigError(f"message_acl[{index}].mark must match ^[A-Za-z0-9_-]+$") from exc
if (
"mark must contain only ASCII letters, digits, underscore, and hyphen"
in message
):
raise ConfigError(
f"message_acl[{index}].mark must match ^[A-Za-z0-9_-]+$"
) from exc
if "send must be either 'urgent' or 'queue'" in message:
raise ConfigError(f"message_acl[{index}].send must be either 'urgent' or 'queue'") from exc
raise ConfigError(
f"message_acl[{index}].send must be either 'urgent' or 'queue'"
) from exc
raise ConfigError(f"message_acl[{index}] is invalid: {exc}") from exc
@ -218,7 +247,9 @@ class AppConfig:
cleanup_interval_seconds: int = 60
api_host: str = "127.0.0.1"
api_port: int = 8000
journal_command: list[str] = field(default_factory=lambda: ["journalctl", "-f", "-o", "json"])
journal_command: list[str] = field(
default_factory=lambda: ["journalctl", "-f", "-o", "json"]
)
log_level: str = "info"
state_file: Path | None = None
@ -229,7 +260,9 @@ class AppConfig:
return f"http://{host}:{self.api_port}"
@classmethod
def from_mapping(cls, raw: Mapping[str, Any], *, base_path: Path | None = None) -> "AppConfig":
def from_mapping(
cls, raw: Mapping[str, Any], *, base_path: Path | None = None
) -> "AppConfig":
app_section = raw.get("application", raw)
api_section = raw.get("api", {})
journal_section = raw.get("journal", {})
@ -245,7 +278,9 @@ class AppConfig:
if storage_section and not isinstance(storage_section, Mapping):
raise ConfigError("storage section must be a mapping")
if "monitored_process_names" in app_section:
raise ConfigError("monitored_process_names is no longer supported; use message_acl")
raise ConfigError(
"monitored_process_names is no longer supported; use message_acl"
)
event_ttl_seconds = _require_positive_int(
app_section.get("event_ttl_seconds", 300), "event_ttl_seconds"
@ -259,7 +294,9 @@ class AppConfig:
if not 1 <= api_port <= 65535:
raise ConfigError("api.port must be between 1 and 65535")
journal_command_value = journal_section.get("command", ["journalctl", "-f", "-o", "json"])
journal_command_value = journal_section.get(
"command", ["journalctl", "-f", "-o", "json"]
)
if not isinstance(journal_command_value, list) or not journal_command_value:
raise ConfigError("journal.command must be a non-empty list")
journal_command: list[str] = []
@ -270,7 +307,11 @@ class AppConfig:
log_level = str(app_section.get("log_level", "info")).strip() or "info"
state_file_value = storage_section.get("state_file") if isinstance(storage_section, Mapping) else None
state_file_value = (
storage_section.get("state_file")
if isinstance(storage_section, Mapping)
else None
)
state_file: Path | None = None
if state_file_value is not None:
if not isinstance(state_file_value, str) or not state_file_value.strip():

View File

@ -15,8 +15,7 @@ from .models import JournalEvent, MessageAclRule
class JournalReader(Protocol):
def stream(self, stop_event: threading.Event) -> Iterator[Mapping[str, Any]]:
...
def stream(self, stop_event: threading.Event) -> Iterator[Mapping[str, Any]]: ...
class NullJournalReader:
@ -87,7 +86,14 @@ class JournalctlReader:
def extract_process_name(entry: Mapping[str, Any]) -> str | None:
for key in ("_COMM", "COMM", "SYSLOG_IDENTIFIER", "process_name", "process", "name"):
for key in (
"_COMM",
"COMM",
"SYSLOG_IDENTIFIER",
"process_name",
"process",
"name",
):
value = entry.get(key)
if isinstance(value, str) and value.strip():
return value.strip()

View File

@ -41,7 +41,9 @@ class MessageAclRule:
if self.send_policy is not None and self.send_policy not in {"urgent", "queue"}:
raise ValueError("send must be either 'urgent' or 'queue'")
if self.mark is not None and not _MARK_PATTERN.fullmatch(self.mark):
raise ValueError("mark must contain only ASCII letters, digits, underscore, and hyphen")
raise ValueError(
"mark must contain only ASCII letters, digits, underscore, and hyphen"
)
if self.cache_policy == "drop":
if self.send_policy is not None or self.mark is not None:
raise ValueError("drop rules must not define send or mark")
@ -52,7 +54,10 @@ class MessageAclRule:
self._pattern = re.compile(self.message_regex)
def matches(self, process_name: str, message: str) -> bool:
process_matches = self.process_name == "*" or self.process_name.casefold() == process_name.casefold()
process_matches = (
self.process_name == "*"
or self.process_name.casefold() == process_name.casefold()
)
return process_matches and self._pattern.search(message) is not None
def to_dict(self) -> dict[str, Any]:

View File

@ -14,7 +14,12 @@ class ApplicationRuntime:
def __init__(self, config: AppConfig, reader=None) -> None:
self.config = config
self.logger = logging.getLogger(__name__)
self.core = ApplicationCore(config, reader=reader or JournalctlReader(config.journal_command, logger=self.logger), logger=self.logger)
self.core = ApplicationCore(
config,
reader=reader
or JournalctlReader(config.journal_command, logger=self.logger),
logger=self.logger,
)
def run(self) -> int:
self.core.start()

View File

@ -9,7 +9,7 @@ from typing import Any
from .cache import EventCache
from .config import AppConfig
from .journal import JournalReader, JournalctlReader, NullJournalReader, build_event
from .journal import JournalReader, JournalctlReader, build_event
from .models import JournalEvent, ServiceStatus
from .state import StateStore
@ -35,11 +35,15 @@ class ApplicationCore:
def __post_init__(self) -> None:
self.logger = self.logger or logging.getLogger(__name__)
self.cache = EventCache()
self.state_store = StateStore(self.config.state_file) if self.config.state_file else None
self.state_store = (
StateStore(self.config.state_file) if self.config.state_file else None
)
self._stop_event = threading.Event()
@classmethod
def from_config_file(cls, path: str, reader: JournalReader | None = None) -> "ApplicationCore":
def from_config_file(
cls, path: str, reader: JournalReader | None = None
) -> "ApplicationCore":
return cls(AppConfig.from_file(path), reader=reader)
def _default_reader(self) -> JournalReader:
@ -55,8 +59,12 @@ class ApplicationCore:
self._running = True
self._persist_state()
self._threads = [
threading.Thread(target=self._collector_loop, name="journal-collector", daemon=True),
threading.Thread(target=self._cleanup_loop, name="cache-cleanup", daemon=True),
threading.Thread(
target=self._collector_loop, name="journal-collector", daemon=True
),
threading.Thread(
target=self._cleanup_loop, name="cache-cleanup", daemon=True
),
]
for thread in self._threads:
thread.start()
@ -72,7 +80,9 @@ class ApplicationCore:
self.start()
try:
while not self._stop_event.wait(0.5):
if self._threads and not any(thread.is_alive() for thread in self._threads):
if self._threads and not any(
thread.is_alive() for thread in self._threads
):
break
finally:
self.stop()

View File

@ -51,14 +51,19 @@ class StateStore:
return None
updated_at, status_json = snapshot_row
events: list[dict[str, Any]] = []
for event_row in conn.execute(
"""
for event_row in conn.execute("""
SELECT id, process_name, message, captured_at, payload_json, acl_json
FROM events
ORDER BY captured_at DESC, id ASC
"""
):
event_id, process_name, message, captured_at, payload_json, acl_json = event_row
"""):
(
event_id,
process_name,
message,
captured_at,
payload_json,
acl_json,
) = event_row
try:
payload = json.loads(payload_json) if payload_json else {}
except json.JSONDecodeError:
@ -101,7 +106,9 @@ class StateStore:
status_mapping = legacy_raw.get("status", {})
events = legacy_raw.get("events", [])
updated_at = legacy_raw.get("updated_at") or datetime.now(timezone.utc).isoformat()
updated_at = (
legacy_raw.get("updated_at") or datetime.now(timezone.utc).isoformat()
)
if not isinstance(status_mapping, dict) or not isinstance(events, list):
raise ValueError(f"Unsupported legacy state file format: {self.path}")
@ -135,17 +142,14 @@ class StateStore:
def _ensure_schema(self, conn: sqlite3.Connection) -> None:
conn.execute("PRAGMA foreign_keys = ON")
conn.execute(
"""
conn.execute("""
CREATE TABLE IF NOT EXISTS snapshot (
id INTEGER PRIMARY KEY CHECK (id = 1),
updated_at TEXT NOT NULL,
status_json TEXT NOT NULL
)
"""
)
conn.execute(
"""
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY,
process_name TEXT NOT NULL,
@ -154,8 +158,7 @@ class StateStore:
payload_json TEXT NOT NULL,
acl_json TEXT NOT NULL DEFAULT '{}'
)
"""
)
""")
self._ensure_events_acl_column(conn)
def _replace_snapshot(
@ -190,7 +193,9 @@ class StateStore:
str(event.get("process_name", "")),
str(event.get("message", "")),
str(event.get("captured_at", "")),
json.dumps(event.get("payload", {}), ensure_ascii=False, default=str),
json.dumps(
event.get("payload", {}), ensure_ascii=False, default=str
),
json.dumps(event.get("acl", {}), ensure_ascii=False, default=str),
)
for event in events
@ -201,14 +206,18 @@ class StateStore:
def _ensure_events_acl_column(self, conn: sqlite3.Connection) -> None:
columns = {row[1] for row in conn.execute("PRAGMA table_info(events)")}
if "acl_json" not in columns:
conn.execute("ALTER TABLE events ADD COLUMN acl_json TEXT NOT NULL DEFAULT '{}'")
conn.execute(
"ALTER TABLE events ADD COLUMN acl_json TEXT NOT NULL DEFAULT '{}'"
)
def _status_from_legacy(self, status: dict[str, Any]) -> ServiceStatus:
started_at_value = status.get("started_at")
started_at: datetime | None
if isinstance(started_at_value, str) and started_at_value.strip():
try:
started_at = datetime.fromisoformat(started_at_value.replace("Z", "+00:00"))
started_at = datetime.fromisoformat(
started_at_value.replace("Z", "+00:00")
)
except ValueError:
started_at = None
else:
@ -219,8 +228,14 @@ class StateStore:
started_at=started_at,
cached_events=int(status.get("cached_events", 0) or 0),
event_ttl_seconds=int(status.get("event_ttl_seconds", 300) or 300),
cleanup_interval_seconds=int(status.get("cleanup_interval_seconds", 60) or 60),
last_error=status.get("last_error") if isinstance(status.get("last_error"), str) else None,
cleanup_interval_seconds=int(
status.get("cleanup_interval_seconds", 60) or 60
),
last_error=(
status.get("last_error")
if isinstance(status.get("last_error"), str)
else None
),
message_acl=self._message_acl_from_legacy(status.get("message_acl")),
)
@ -236,7 +251,11 @@ class StateStore:
cache_policy = item.get("cache")
send_policy = item.get("send")
mark = item.get("mark")
if not isinstance(process_name, str) or not isinstance(message_regex, str) or not isinstance(cache_policy, str):
if (
not isinstance(process_name, str)
or not isinstance(message_regex, str)
or not isinstance(cache_policy, str)
):
continue
try:
rules.append(
@ -244,7 +263,9 @@ class StateStore:
process_name=process_name,
message_regex=message_regex,
cache_policy=cache_policy,
send_policy=send_policy if isinstance(send_policy, str) else None,
send_policy=(
send_policy if isinstance(send_policy, str) else None
),
mark=mark if isinstance(mark, str) else None,
)
)

View File

@ -22,7 +22,9 @@ def test_api_exposes_events_and_status() -> None:
{
"_COMM": "sshd",
"MESSAGE": "accepted",
"__REALTIME_TIMESTAMP": int(datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() * 1_000_000),
"__REALTIME_TIMESTAMP": int(
datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() * 1_000_000
),
}
)
@ -48,7 +50,9 @@ def test_api_health_reports_ok() -> None:
def test_api_state_returns_persisted_snapshot(tmp_path) -> None:
state_path = tmp_path / "state.sqlite"
config = AppConfig(message_acl=[MessageAclRule("sshd", ".*", "drop")], state_file=state_path)
config = AppConfig(
message_acl=[MessageAclRule("sshd", ".*", "drop")], state_file=state_path
)
store = StateStore(state_path)
store.write(
status=ApplicationCore(config).status(),
@ -59,7 +63,13 @@ def test_api_state_returns_persisted_snapshot(tmp_path) -> None:
"message": "accepted",
"captured_at": "2026-01-01T00:00:00+00:00",
"payload": {"MESSAGE": "accepted"},
"acl": {"process_name": "sshd", "message_regex": "accepted", "cache": "cache", "send": "urgent", "mark": "scan123"},
"acl": {
"process_name": "sshd",
"message_regex": "accepted",
"cache": "cache",
"send": "urgent",
"mark": "scan123",
},
}
],
)

View File

@ -10,11 +10,10 @@ from typer.testing import CliRunner
from journal_event_collector import cli
from journal_event_collector.api import create_app
from journal_event_collector.config import AppConfig
from journal_event_collector.models import JournalEvent, MessageAclRule
from journal_event_collector.models import MessageAclRule
from journal_event_collector.service import ApplicationCore
from journal_event_collector.state import StateStore
runner = CliRunner()
@ -66,7 +65,9 @@ def test_cli_run_help_shows_default_config_path() -> None:
def test_cli_status_and_events_can_query_api(monkeypatch) -> None:
config = AppConfig(message_acl=[MessageAclRule("sshd", "accepted", "cache", "urgent", "scan123")])
config = AppConfig(
message_acl=[MessageAclRule("sshd", "accepted", "cache", "urgent", "scan123")]
)
core = ApplicationCore(config)
core.ingest(
{
@ -84,8 +85,12 @@ def test_cli_status_and_events_can_query_api(monkeypatch) -> None:
monkeypatch.setattr(cli, "urlopen", fake_urlopen)
status_result = runner.invoke(cli.app, ["status", "--api-base-url", "http://api.local"])
events_result = runner.invoke(cli.app, ["events", "--api-base-url", "http://api.local"])
status_result = runner.invoke(
cli.app, ["status", "--api-base-url", "http://api.local"]
)
events_result = runner.invoke(
cli.app, ["events", "--api-base-url", "http://api.local"]
)
assert status_result.exit_code == 0
assert json.loads(status_result.output)["cached_events"] == 1
@ -150,7 +155,14 @@ state_file = "{state_path.name}"
store = StateStore(settings.state_file)
store.write(
status=ApplicationCore(settings).status(),
events=[{"id": "1", "process_name": "sshd", "message": "accepted", "captured_at": "2026-01-01T00:00:00+00:00"}],
events=[
{
"id": "1",
"process_name": "sshd",
"message": "accepted",
"captured_at": "2026-01-01T00:00:00+00:00",
}
],
)
status_result = runner.invoke(cli.app, ["status", "--config", str(config_path)])

View File

@ -56,11 +56,15 @@ def test_app_config_defaults_missing_message_acl_to_drop_all() -> None:
def test_app_config_rejects_legacy_whitelist() -> None:
with pytest.raises(ConfigError, match="monitored_process_names is no longer supported"):
with pytest.raises(
ConfigError, match="monitored_process_names is no longer supported"
):
AppConfig.from_mapping(
{
"application": {"monitored_process_names": ["sshd"]},
"message_acl": ['cache process sshd regexp "accepted" send urgent mark scan123'],
"message_acl": [
'cache process sshd regexp "accepted" send urgent mark scan123'
],
}
)
@ -91,7 +95,9 @@ state_file = "./state/state.sqlite"
def test_app_config_builds_cli_api_base_url() -> None:
config = AppConfig.from_mapping(
{
"message_acl": ['cache process sshd regexp "accepted" send urgent mark scan123'],
"message_acl": [
'cache process sshd regexp "accepted" send urgent mark scan123'
],
"api": {"host": "0.0.0.0", "port": 9000},
}
)
@ -117,9 +123,7 @@ def test_app_config_parses_message_acl() -> None:
def test_app_config_rejects_invalid_message_acl_regex() -> None:
with pytest.raises(ConfigError, match=r"message_acl\[0\]\.message_regex"):
AppConfig.from_mapping(
{
"message_acl": ['cache process sshd regexp "(" send urgent mark scan123']
}
{"message_acl": ['cache process sshd regexp "(" send urgent mark scan123']}
)
@ -127,16 +131,14 @@ def test_app_config_rejects_invalid_mark() -> None:
with pytest.raises(ConfigError, match=r"message_acl\[0\]\.mark"):
AppConfig.from_mapping(
{
"message_acl": ['cache process sshd regexp "accepted" send urgent mark "bad mark!"']
"message_acl": [
'cache process sshd regexp "accepted" send urgent mark "bad mark!"'
]
}
)
def test_app_config_accepts_drop_rule_without_send_and_mark() -> None:
config = AppConfig.from_mapping(
{
"message_acl": ['drop process sshd regexp ".*"']
}
)
config = AppConfig.from_mapping({"message_acl": ['drop process sshd regexp ".*"']})
assert config.message_acl[0].cache_policy == "drop"

View File

@ -1,12 +1,18 @@
from __future__ import annotations
from datetime import datetime, timezone