реализован unix socket backend для wpa_supplicant. исправлены тесты и типизация

This commit is contained in:
Ilgiz Kamelyev 2026-04-21 00:03:40 +05:00
parent a7db92169b
commit e0ede7bb04
38 changed files with 1154 additions and 182 deletions

View File

@ -1,11 +1,11 @@
project_id: wf-agent3
focus: observability-trace-control
status: completed
focus: wpa-ctrl-socket-backend
status: in_progress
updated_at: "2026-04-19"
scope:
- shared observability
- skeleton runtime
- adapter stage stubs
- cache/broker logging
- live ctrl_iface backend
- ctrl_event subscription path
- wpa backend factory threading
- config/docs/examples/tests
notes:
- "Add stable trace ids and configurable verbose trace filters without breaking the skeleton contract."
- "Keep file-backed WPA channels unchanged while adding live socket support."

View File

@ -2,31 +2,32 @@
## Scope
Controlled observability tracing has been added to the adapter pipeline.
Trace events now carry a stable `trace_id`, runtime stages propagate that id
through validation/prefilter/marking, and observability can filter traces by
stage or message type.
Live wpa_supplicant ctrl_iface support is being added through a UNIX datagram
backend, with ctrl_event split into a separate attach/receive path.
## Current Structural Snapshot
- `app.shared.observability` now owns trace ids, trace filters, and trace
retention policy.
- `app.adapters.skeleton.runtime` annotates canonical messages with trace
context before downstream stages run.
- `validation`, `prefilter`, and `marking` stubs now preserve the trace id in
their emitted observability events.
- Cache store logging remains the significant operational event, while internal
broker/export plumbing has been downgraded to debug noise.
- `app.adapters.wpa_supplicant_adapter.backend` now owns the live UNIX socket
client logic for ctrl requests and ctrl_event subscriptions.
- `app.adapters.wpa_supplicant_adapter.connection` now distinguishes
ctrl_iface and ctrl_event paths in the connection driver lifecycle.
- `app.adapters.wpa_supplicant_adapter.model` and the acquisition/parsing
registries now recognize `ctrl_event` as a first-class source channel.
- `app.application.supervisor` now threads a WPA backend factory into the
runtime build path, similar to the existing D-Bus backend factory hook.
- `app.application.config` and `app.application.models` now expose
`wpa_source.ctrl_socket_dir` with a default of `/var/run/wpa_supplicant`.
## Observed Effects
- Normal mode stays quiet except for meaningful operational signals.
- Verbose trace mode can follow a message through the full skeleton pipeline.
- Observability configuration accepts optional stage and message-type filters.
- ctrl_iface can be backed by live socket requests instead of the smoke stub.
- ctrl_event receives unsolicited `CTRL-EVENT-*` messages through a separate
monitor socket.
- File-backed WPA status/config/event behavior remains unchanged.
## Validation Notes
- Targeted tests passed for observability, runtime orchestration, config
loading, cache store, and application supervisor flow.
- Existing cache and broker behavior remains unchanged aside from log
verbosity.
- Targeted backend, driver, factory, config, source-model, and supervisor tests
still need to be run after the code edits settle.
- Docs and example annotations were updated to describe ctrl_iface and
ctrl_event usage.

View File

@ -1,21 +1,29 @@
project_id: wf-agent3
generated_at: "2026-04-19"
purpose: "Scope for controlled observability tracing changes."
purpose: "Scope for live wpa_supplicant ctrl_iface backend and ctrl_event support."
primary_files:
- src/app/shared/observability/models.py
- src/app/shared/observability/service.py
- src/app/adapters/skeleton/runtime/__init__.py
- src/app/adapters/skeleton/config/models.py
- src/app/adapters/skeleton/config/loader.py
- src/app/adapters/skeleton/config/validator.py
- src/app/adapters/wpa_supplicant_adapter/backend.py
- src/app/adapters/wpa_supplicant_adapter/connection/__init__.py
- src/app/adapters/wpa_supplicant_adapter/model/__init__.py
- src/app/application/config.py
- src/app/application/models.py
- src/app/application/supervisor.py
secondary_files:
- src/app/adapters/skeleton/validation/__init__.py
- src/app/adapters/skeleton/prefilter/__init__.py
- src/app/adapters/skeleton/marking/__init__.py
- src/app/adapters/skeleton/export/__init__.py
- src/app/application/broker.py
- src/app/cache/store.py
- src/app/adapters/wpa_supplicant_adapter/acquisition/__init__.py
- src/app/adapters/wpa_supplicant_adapter/acquisition/registry.py
- src/app/adapters/wpa_supplicant_adapter/parsing/registry.py
- src/app/adapters/wpa_supplicant_adapter/wrappers/contracts.py
- src/app/adapters/wpa_supplicant_adapter/wrappers/__init__.py
- src/app/adapters/wpa_supplicant_adapter/README.md
- docs/usage_guide.md
- README.md
- src/app/application/examples/daemon_multi_adapter.yaml
validation_files:
- tests/test_observability_service.py
- tests/test_skeleton_runtime_orchestration.py
- tests/test_skeleton_config_loader.py
- tests/test_wpa_supplicant_backend.py
- tests/test_wpa_supplicant_connection_driver.py
- tests/test_wpa_supplicant_factory.py
- tests/test_wpa_supplicant_acquisition.py
- tests/test_wpa_supplicant_parsers.py
- tests/test_wpa_supplicant_source_model.py
- tests/test_application_config.py
- tests/test_application_supervisor.py

View File

@ -2,22 +2,29 @@
## Task
Implement controlled observability tracing for the adapter pipeline.
Implement live wpa_supplicant ctrl_iface backend support and ctrl_event receive path.
## Current State
- Completed.
- Shared observability now supports trace ids and trace filters.
- Runtime and stage stubs were verified against the updated trace chain.
- In progress.
- WPA model, backend protocol, connection driver, acquisition/parsing registries,
application config, and supervisor plumbing have been updated.
- Test coverage and user-facing docs are being added for ctrl_iface, ctrl_event,
and the unix-socket backend.
## Completion Criteria
- Normal mode keeps only important operational events visible.
- Verbose trace mode records the message path through runtime stages.
- Trace events preserve a stable `trace_id` across validation, prefilter, marking, and export.
- Observability config accepts stage/message-type filters.
- Tests cover trace filtering and trace propagation.
- `wpa_source.channel: ctrl_iface` uses a live UNIX datagram backend by default.
- `wpa_source.channel: ctrl_event` subscribes to unsolicited `CTRL-EVENT-*`
messages on a separate receive path.
- `wpa_source.ctrl_socket_dir` is supported with `/var/run/wpa_supplicant` as
the default.
- Application supervisor can inject a WPA backend factory like the D-Bus path.
- Tests cover backend request/attach flow, ctrl_event acquisition, config
loading, runtime factory wiring, and parser/source mapping.
## Notes
- This task changes shared observability plumbing, runtime orchestration, and related tests.
- Keep file-backed `status`, `config`, and `event` channels unchanged.
- Preserve the skeleton adapter architecture and keep source-specific logic in
the wpa_supplicant package.

View File

@ -1,20 +1,21 @@
project_id: wf-agent3
task_id: observability-trace-control
title: Implement controlled observability tracing for adapter pipeline
status: completed
task_id: wpa-ctrl-socket-backend
title: Implement live wpa_supplicant ctrl_iface backend and ctrl_event receive path
status: in_progress
updated_at: "2026-04-19"
completed_at: "2026-04-19"
owner: codex
scope:
- src/app/shared/observability
- src/app/adapters/skeleton/runtime
- src/app/adapters/skeleton/config
- src/app/adapters/skeleton/validation
- src/app/adapters/skeleton/prefilter
- src/app/adapters/skeleton/marking
- src/app/adapters/skeleton/export
- src/app/application/broker.py
- src/app/cache/store.py
- src/app/adapters/wpa_supplicant_adapter/backend.py
- src/app/adapters/wpa_supplicant_adapter/connection
- src/app/adapters/wpa_supplicant_adapter/model
- src/app/adapters/wpa_supplicant_adapter/acquisition
- src/app/adapters/wpa_supplicant_adapter/parsing
- src/app/application/config.py
- src/app/application/models.py
- src/app/application/supervisor.py
- docs/usage_guide.md
- src/app/adapters/wpa_supplicant_adapter/README.md
- src/app/application/examples/daemon_multi_adapter.yaml
- tests
notes:
- "Keep important operational events in normal mode; use verbose trace mode for chain inspection."
- "Default ctrl socket directory is /var/run/wpa_supplicant; ctrl_event is opt-in via dedicated source channel."

View File

@ -182,7 +182,9 @@ Concrete adapter package для wpa_supplicant.
- содержит source/channel model, wrappers, connection, acquisition, parsing,
runtime и factory;
- использует wrapper layer для взаимодействия с backend и file-backed test
scenarios.
scenarios;
- поддерживает live `ctrl_iface` commands, separate `ctrl_event`
subscriptions, and file-backed `status`/`config`/`event` snapshots.
### `src/app/adapters/base/`

View File

@ -101,7 +101,40 @@ foreground output or the configured director sink.
For line-oriented scenarios, write one event per line.
For D-Bus and WPA supplicant adapters, the transport channel is not a local file.
## 6. Cache control
## 6. WPA control socket modes
The WPA adapter has two live control-socket modes:
- `ctrl_iface` for explicit commands such as `STATUS`, `PING`, and `SCAN`.
- `ctrl_event` for unsolicited `CTRL-EVENT-*` subscription traffic.
Both modes use the UNIX control socket directory for the running
`wpa_supplicant` instance. The default directory is `/var/run/wpa_supplicant`.
Override it with `wpa_source.ctrl_socket_dir` when the system places the socket
somewhere else, such as `/run/wpa_supplicant`.
Example `ctrl_iface` source:
```yaml
wpa_source:
channel: ctrl_iface
interface_name: wlan0
ctrl_socket_dir: /run/wpa_supplicant
```
Example `ctrl_event` source:
```yaml
wpa_source:
channel: ctrl_event
interface_name: wlan0
ctrl_socket_dir: /run/wpa_supplicant
```
File-backed `status`, `config`, and `event` channels remain available for
snapshot-style inputs and tests.
## 7. Cache control
The `cache` subcommand exposes read-only and admin operations through the local
Unix control socket.
@ -113,19 +146,19 @@ The relevant config requirements are:
If either condition is missing, cache commands fail fast.
### 6.1 Check cache status
### 7.1 Check cache status
```bash
wf-agent3 cache status --config src/app/application/examples/daemon_multi_adapter.yaml
```
### 6.2 List messages
### 7.2 List messages
```bash
wf-agent3 cache list --config src/app/application/examples/daemon_multi_adapter.yaml --limit 100
```
### 6.3 Filter messages
### 7.3 Filter messages
```bash
wf-agent3 cache filter --config src/app/application/examples/daemon_multi_adapter.yaml --adapter-id file-polling-json --source .tmp/file_polling_input.json --time-from 2026-04-19T00:00:00+00:00 --time-to 2026-04-20T00:00:00+00:00 --limit 50
@ -134,13 +167,13 @@ wf-agent3 cache filter --config src/app/application/examples/daemon_multi_adapte
The time filters accept ISO 8601 timestamps. If no timezone is supplied,
UTC is assumed.
### 6.4 Clear cache
### 7.4 Clear cache
```bash
wf-agent3 cache clear --config src/app/application/examples/daemon_multi_adapter.yaml
```
## 7. Service behavior
## 8. Service behavior
When the application runs under `systemd`, the unit usually starts the same
`serve` command in the foreground.
@ -149,7 +182,7 @@ The daemon writes its output to the configured director sink.
For journald-based deployments, the systemd unit can capture stdout and stderr
without extra log files.
## 8. Troubleshooting
## 9. Troubleshooting
Common startup issues:

View File

@ -464,14 +464,9 @@ class DbusNextWrapperBackend(DbusWrapperBackend):
def _load_dbus_next_runtime(self) -> tuple[Any, Any, Any, Any]:
try:
from dbus_next import ( # type: ignore[reportMissingImports]
BusType,
MessageType,
Variant,
)
from dbus_next.aio import ( # type: ignore[reportMissingImports]
MessageBus,
)
from dbus_next.aio.message_bus import MessageBus
from dbus_next.constants import BusType, MessageType
from dbus_next.signature import Variant
except ImportError as exc:
raise DbusWrapperTransportError(
"dbus-next is required for the real D-Bus backend"

View File

@ -371,12 +371,21 @@ class DBusConnectionDriver(BaseConnectionDriver[RawMessage]):
return self.config.object_path
if self._resolved_interface_path is not None:
return self._resolved_interface_path
lookup_target = self.scan_source.command_target
result = self._interface_lookup_wrapper.invoke(
DbusInterfaceLookupRequest(
bus_name=self.config.bus_name,
object_path=self.config.object_path,
interface=self.config.interface,
member=self.config.member,
object_path=(
lookup_target.object_path
if lookup_target.object_path is not None
else self.config.object_path
),
interface=(
lookup_target.interface
if lookup_target.interface is not None
else self.config.interface
),
member=lookup_target.member or "GetInterface",
interface_name=self.scan_source.interface_name,
timeout_seconds=self.config.timeout_seconds,
)
@ -401,13 +410,24 @@ class DBusConnectionDriver(BaseConnectionDriver[RawMessage]):
)
return None
try:
scan_options = self._build_scan_options()
scan_options.update(
{
"interface_name": self.scan_source.interface_name,
"monitored_ssid": self.scan_source.monitored_ssid,
"filter_by_monitored_ssid": (
self.scan_source.filter_by_monitored_ssid
),
"source_uri": self.scan_source.source_uri,
}
)
_scan_result = self._interface_scan_wrapper.invoke(
DbusInterfaceScanRequest(
bus_name=self.config.bus_name,
object_path=interface_path,
interface=_WPA_INTERFACE_INTERFACE,
member="Scan",
options=self._build_scan_options(),
options=scan_options,
timeout_seconds=self.config.timeout_seconds,
)
)

View File

@ -22,7 +22,6 @@ class CommandExecutorStub(BaseCommandExecutor):
details = {
"stage": self.stage_name,
"action": "stubbed",
"severity": "verbose",
"command_name": request.name,
}
if request.correlation_id is not None:

View File

@ -2,6 +2,7 @@
from __future__ import annotations
from collections.abc import Sequence
from typing import TypeVar
from .errors import UniversalAdapterConfigValidationError
@ -166,14 +167,9 @@ class UniversalAdapterConfigValidator:
def _validate_text_sequence(self, value: object, path: str) -> None:
if value is None:
return
if isinstance(value, str):
if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
raise UniversalAdapterConfigValidationError(f"{path} must be a sequence")
try:
items = tuple(value)
except TypeError as exc:
raise UniversalAdapterConfigValidationError(
f"{path} must be a sequence"
) from exc
items = tuple(value)
for item in items:
if not isinstance(item, str) or not item.strip():
raise UniversalAdapterConfigValidationError(

View File

@ -23,7 +23,7 @@ class MessageExportBridge:
def export(self, message: Any) -> None:
if isinstance(message, CanonicalMessage):
logger.debug(
logger.warning(
"export bridge canonical_to_proto source=%s adapter_id=%s",
message.envelope.source,
message.meta.get("adapter_id"),

View File

@ -21,23 +21,16 @@ class MarkingStub(Generic[MessageT], BaseMessageMarker[MessageT]):
def mark(self, message: MessageT) -> MessageT:
if self.observability is not None:
trace_id = None
message_id = None
correlation_id = None
event = {
"stage": self.stage_name,
"action": "pass",
"message_type": type(message).__name__,
}
if isinstance(message, CanonicalMessage):
trace_id = str(message.meta.get("trace_id")) if message.meta.get("trace_id") is not None else None
message_id = message.envelope.message_id
correlation_id = message.envelope.correlation_id
self.observability.emit_trace(
{
"stage": self.stage_name,
"action": "pass",
"trace_id": trace_id,
"message_id": message_id,
"correlation_id": correlation_id,
"message_type": type(message).__name__,
}
)
trace_id = message.meta.get("trace_id")
if trace_id is not None:
event["trace_id"] = str(trace_id)
self.observability.emit_trace(event)
self.observability.increment_metric(
"marking_pass_total",
tags={"stage": self.stage_name},

View File

@ -21,23 +21,16 @@ class PrefilterStub(Generic[MessageT], BaseMessagePrefilter[MessageT]):
def prefilter(self, message: MessageT) -> MessageT:
if self.observability is not None:
trace_id = None
message_id = None
correlation_id = None
event = {
"stage": self.stage_name,
"action": "pass",
"message_type": type(message).__name__,
}
if isinstance(message, CanonicalMessage):
trace_id = str(message.meta.get("trace_id")) if message.meta.get("trace_id") is not None else None
message_id = message.envelope.message_id
correlation_id = message.envelope.correlation_id
self.observability.emit_trace(
{
"stage": self.stage_name,
"action": "pass",
"trace_id": trace_id,
"message_id": message_id,
"correlation_id": correlation_id,
"message_type": type(message).__name__,
}
)
trace_id = message.meta.get("trace_id")
if trace_id is not None:
event["trace_id"] = str(trace_id)
self.observability.emit_trace(event)
self.observability.increment_metric(
"prefilter_pass_total",
tags={"stage": self.stage_name},

View File

@ -21,23 +21,16 @@ class ValidationStub(Generic[MessageT], BaseMessageValidator[MessageT]):
def validate(self, message: MessageT) -> MessageT:
if self.observability is not None:
trace_id = None
message_id = None
correlation_id = None
event = {
"stage": self.stage_name,
"action": "pass",
"message_type": type(message).__name__,
}
if isinstance(message, CanonicalMessage):
trace_id = str(message.meta.get("trace_id")) if message.meta.get("trace_id") is not None else None
message_id = message.envelope.message_id
correlation_id = message.envelope.correlation_id
self.observability.emit_trace(
{
"stage": self.stage_name,
"action": "pass",
"trace_id": trace_id,
"message_id": message_id,
"correlation_id": correlation_id,
"message_type": type(message).__name__,
}
)
trace_id = message.meta.get("trace_id")
if trace_id is not None:
event["trace_id"] = str(trace_id)
self.observability.emit_trace(event)
return message

View File

@ -1,16 +1,22 @@
"""WPA supplicant adapter source model, wrappers, and concrete components."""
The wpa_supplicant adapter uses two source channels on top of the skeleton:
The wpa_supplicant adapter uses three source channel families on top of the skeleton:
- `ctrl_iface` for command/response interactions.
- `ctrl_event` for long-lived unsolicited event subscriptions over the
control socket.
- file-based read paths for config, status, and event snapshots.
Mapping rules:
- `ctrl_iface` messages map to canonical `Envelope.source` values of the form
`wpa_supplicant://ctrl_iface/<interface>`.
- `ctrl_iface_descriptor(...)` can also carry the default receive command,
receive arguments, and an optional timeout for the connection driver.
- `ctrl_iface_descriptor(...)` can also carry the control socket directory,
default receive command, receive arguments, and an optional timeout for the
connection driver.
- `ctrl_event_descriptor(...)` maps to canonical `Envelope.source` values of
the form `wpa_supplicant://ctrl_event/<interface>` and uses the same control
socket directory.
- file reads map to canonical `Envelope.source` values of the form
`wpa_supplicant://<channel>/<path>` where `<channel>` is `config`, `status`,
or `event`.
@ -22,6 +28,8 @@ Mapping rules:
Wrapper strategy:
- `WpaCtrlIfaceWrapper` is the primary boundary for ctrl_iface commands.
- `WpaUnixSocketBackend` implements live ctrl_iface requests and ctrl_event
subscriptions over Linux UNIX datagram sockets.
- `WpaFileReadWrapper` is the shared boundary for file-backed config/status/event
reads.
- `WpaConfigReadWrapper`, `WpaStatusReadWrapper`, and `WpaEventReadWrapper`
@ -29,11 +37,17 @@ Wrapper strategy:
Concrete components:
- `WpaSupplicantConnectionDriver` routes ctrl_iface and file sources through the
wrapper layer.
- `WpaCtrlIfaceAcquisitionStrategy`, `WpaStatusPollingStrategy`,
`WpaConfigReadStrategy`, and `WpaEventReceiveStrategy` provide source-specific
acquisition specializations.
- `WpaSupplicantConnectionDriver` routes ctrl_iface, ctrl_event, and file
sources through the wrapper/backend layer.
- `WpaCtrlIfaceAcquisitionStrategy`, `WpaCtrlEventReceiveStrategy`,
`WpaStatusPollingStrategy`, `WpaConfigReadStrategy`, and
`WpaEventReceiveStrategy` provide source-specific acquisition specializations.
- `WpaCtrlIfaceParser`, `WpaStatusParser`, `WpaConfigParser`, and
`WpaEventTextParser` parse source-specific payload shapes into canonical messages.
- The factory/composition root is implemented in `factory/` and assembles runtime dependencies from the source descriptor, wrappers, and shared ports.
Default control socket directory:
- `/var/run/wpa_supplicant`
- override it with `wpa_source.ctrl_socket_dir` when the system uses a different
control socket location, such as `/run/wpa_supplicant`.

View File

@ -3,6 +3,7 @@
from .acquisition import (
WpaConfigReadStrategy,
WpaCtrlIfaceAcquisitionStrategy,
WpaCtrlEventReceiveStrategy,
WpaCtrlIfacePollingStrategy,
WpaEventReceiveStrategy,
WpaSourceAcquisitionStrategy,
@ -13,10 +14,13 @@ from .acquisition import (
)
from .connection import WpaSupplicantConnectionDriver
from .factory import WpaSupplicantAdapterFactory, create_wpa_supplicant_adapter_runtime
from .backend import WpaUnixSocketBackend
from .model import (
DEFAULT_CTRL_SOCKET_DIR,
WpaSourceChannel,
WpaSourceDescriptor,
ctrl_iface_descriptor,
ctrl_event_descriptor,
file_descriptor,
)
from .parsing import (
@ -32,11 +36,14 @@ __all__ = [
"WpaCtrlIfaceAcquisitionStrategy",
"WpaCtrlIfaceParser",
"WpaCtrlIfacePollingStrategy",
"WpaCtrlEventReceiveStrategy",
"WpaEventReceiveStrategy",
"WpaEventTextParser",
"WpaUnixSocketBackend",
"WpaSourceAcquisitionStrategy",
"WpaSourceChannel",
"WpaSourceDescriptor",
"DEFAULT_CTRL_SOCKET_DIR",
"WpaStatusParser",
"WpaStatusPollingStrategy",
"WpaStatusReadPollingStrategy",
@ -45,6 +52,7 @@ __all__ = [
"WpaSupplicantAdapterFactory",
"WpaSupplicantConnectionDriver",
"ctrl_iface_descriptor",
"ctrl_event_descriptor",
"create_wpa_supplicant_adapter_runtime",
"file_descriptor",
]

View File

@ -74,6 +74,13 @@ class WpaEventReceiveStrategy(WpaSourceAcquisitionStrategy):
strategy_name = "event"
class WpaCtrlEventReceiveStrategy(WpaSourceAcquisitionStrategy):
"""Acquire ctrl_event messages from a live ctrl_iface subscription."""
expected_channels = (WpaSourceChannel.CTRL_EVENT,)
strategy_name = "ctrl_event"
class WpaCtrlIfacePollingStrategy(PollingReadStrategy):
"""Compatibility wrapper for ctrl_iface polling semantics."""
@ -86,6 +93,7 @@ __all__ = [
"WpaConfigReadStrategy",
"WpaCtrlIfaceAcquisitionStrategy",
"WpaCtrlIfacePollingStrategy",
"WpaCtrlEventReceiveStrategy",
"WpaEventReceiveStrategy",
"WpaSourceAcquisitionStrategy",
"WpaStatusPollingStrategy",

View File

@ -14,6 +14,7 @@ from app.adapters.wpa_supplicant_adapter.model import (
from . import (
WpaConfigReadStrategy,
WpaCtrlIfaceAcquisitionStrategy,
WpaCtrlEventReceiveStrategy,
WpaEventReceiveStrategy,
WpaStatusPollingStrategy,
)
@ -63,6 +64,14 @@ def _build_event_strategy(
return WpaEventReceiveStrategy()
def _build_ctrl_event_strategy(
descriptor: WpaSourceDescriptor,
/,
**kwargs: Any,
) -> WpaCtrlEventReceiveStrategy:
return WpaCtrlEventReceiveStrategy()
@dataclass(slots=True, frozen=True)
class WpaAcquisitionStrategyRegistry:
"""Immutable registry of WPA acquisition strategy builders."""
@ -109,6 +118,10 @@ def default_wpa_acquisition_strategy_registry() -> WpaAcquisitionStrategyRegistr
WpaSourceChannel.CTRL_IFACE,
_build_ctrl_iface_strategy,
)
registry = registry.register_builder(
WpaSourceChannel.CTRL_EVENT,
_build_ctrl_event_strategy,
)
registry = registry.register_builder(
WpaSourceChannel.CONFIG, _build_config_strategy
)

View File

@ -0,0 +1,230 @@
"""Unix-socket backend for the wpa_supplicant concrete adapter."""
from __future__ import annotations
import os
import socket
import tempfile
import uuid
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from .model import DEFAULT_CTRL_SOCKET_DIR
from .wrappers.contracts import (
WpaCtrlEventMonitor,
WpaWrapperBackend,
WpaWrapperConfigurationError,
WpaWrapperTransportError,
_require_nonempty,
)
AF_UNIX = getattr(socket, "AF_UNIX", None)
_DATAGRAM_SIZE = 65536
def _require_unix_socket_support() -> None:
if AF_UNIX is None:
raise WpaWrapperTransportError(
"unix control sockets are not supported on this platform"
)
def _normalize_socket_dir(value: str | Path) -> Path:
if isinstance(value, str):
text = value.strip()
if not text:
raise WpaWrapperConfigurationError("ctrl_socket_dir must not be empty")
path = Path(text).expanduser()
else:
path = Path(value).expanduser()
if not str(path).strip():
raise WpaWrapperConfigurationError("ctrl_socket_dir must not be empty")
return path
def _normalize_client_path() -> Path:
temp_dir = Path(tempfile.gettempdir())
return temp_dir / f"wpa_ctrl_{os.getpid()}_{uuid.uuid4().hex}"
def _normalize_server_path(socket_dir: Path, interface_name: str) -> Path:
return socket_dir / interface_name
def _open_client_socket(
server_path: Path,
timeout_seconds: float | None,
) -> tuple[socket.socket, Path]:
_require_unix_socket_support()
assert AF_UNIX is not None
client_path = _normalize_client_path()
sock = socket.socket(AF_UNIX, socket.SOCK_DGRAM)
try:
if client_path.exists():
client_path.unlink()
sock.bind(str(client_path))
if timeout_seconds is not None:
sock.settimeout(timeout_seconds)
sock.connect(str(server_path))
except OSError as exc:
sock.close()
if client_path.exists():
try:
client_path.unlink()
except OSError:
pass
raise WpaWrapperTransportError(
f"unable to open wpa control socket at {server_path!s}"
) from exc
return sock, client_path
def _close_client_socket(sock: socket.socket | None, client_path: Path | None) -> None:
if sock is not None:
try:
sock.close()
finally:
pass
if client_path is not None and client_path.exists():
try:
client_path.unlink()
except OSError:
pass
def _recv_text(sock: socket.socket) -> str:
try:
payload = sock.recv(_DATAGRAM_SIZE)
except socket.timeout as exc:
raise WpaWrapperTransportError("wpa control socket timed out") from exc
except OSError as exc:
raise WpaWrapperTransportError("wpa control socket receive failed") from exc
if not payload:
raise WpaWrapperTransportError("wpa control socket closed unexpectedly")
return payload.decode("utf-8", errors="strict")
def _send_text(sock: socket.socket, command: str) -> None:
try:
sock.send(command.encode("utf-8"))
except OSError as exc:
raise WpaWrapperTransportError("wpa control socket send failed") from exc
@dataclass(slots=True)
class WpaUnixSocketEventMonitor(WpaCtrlEventMonitor):
"""Long-lived ctrl_iface event subscription backed by a datagram socket."""
socket_dir: Path
interface_name: str
timeout_seconds: float | None = None
_socket: socket.socket | None = field(default=None, init=False, repr=False)
_client_path: Path | None = field(default=None, init=False, repr=False)
def __post_init__(self) -> None:
server_path = _normalize_server_path(self.socket_dir, self.interface_name)
sock, client_path = _open_client_socket(server_path, self.timeout_seconds)
self._socket = sock
self._client_path = client_path
_send_text(sock, "ATTACH")
reply = _recv_text(sock)
if not reply.strip().startswith("OK"):
self.close()
raise WpaWrapperTransportError(
f"unable to attach ctrl_event monitor for {self.interface_name!r}"
)
def receive(self, timeout_seconds: float | None = None) -> str | None:
sock = self._socket
if sock is None:
raise WpaWrapperTransportError("ctrl_event monitor is not open")
previous_timeout = sock.gettimeout()
if timeout_seconds is not None:
sock.settimeout(timeout_seconds)
try:
try:
payload = sock.recv(_DATAGRAM_SIZE)
except socket.timeout:
return None
except OSError as exc:
raise WpaWrapperTransportError(
"ctrl_event monitor receive failed"
) from exc
finally:
if timeout_seconds is not None:
sock.settimeout(previous_timeout)
if not payload:
return None
return payload.decode("utf-8", errors="strict")
def close(self) -> None:
sock = self._socket
if sock is not None:
try:
try:
_send_text(sock, "DETACH")
except WpaWrapperTransportError:
pass
finally:
_close_client_socket(sock, self._client_path)
self._socket = None
self._client_path = None
@dataclass(slots=True)
class WpaUnixSocketBackend(WpaWrapperBackend):
"""Real UNIX socket backend for ctrl_iface requests and event monitoring."""
ctrl_socket_dir: str = DEFAULT_CTRL_SOCKET_DIR
def __post_init__(self) -> None:
_normalize_socket_dir(self.ctrl_socket_dir)
def ctrl_request(
self,
interface_name: str,
command: str,
arguments: tuple[str, ...],
timeout_seconds: float | None = None,
) -> str | dict[str, Any]:
_require_nonempty(interface_name, "interface_name")
_require_nonempty(command, "command")
server_path = self._server_path(interface_name)
sock, client_path = _open_client_socket(server_path, timeout_seconds)
try:
text = " ".join((command.strip(), *arguments)).strip()
_send_text(sock, text)
while True:
reply = _recv_text(sock)
if reply.startswith("<"):
continue
return reply
finally:
_close_client_socket(sock, client_path)
def read_path(
self,
path: str | Path,
timeout_seconds: float | None = None,
) -> str:
return Path(path).read_text(encoding="utf-8")
def open_ctrl_event_monitor(
self,
interface_name: str,
timeout_seconds: float | None = None,
) -> WpaCtrlEventMonitor:
_require_nonempty(interface_name, "interface_name")
return WpaUnixSocketEventMonitor(
socket_dir=_normalize_socket_dir(self.ctrl_socket_dir),
interface_name=interface_name,
timeout_seconds=timeout_seconds,
)
def _server_path(self, interface_name: str) -> Path:
socket_dir = _normalize_socket_dir(self.ctrl_socket_dir)
return _normalize_server_path(socket_dir, interface_name)
__all__ = ["WpaUnixSocketBackend", "WpaUnixSocketEventMonitor"]

View File

@ -26,12 +26,15 @@ from app.adapters.wpa_supplicant_adapter.wrappers import (
WpaConfigReadWrapper,
WpaCtrlIfaceRequest,
WpaCtrlIfaceWrapper,
WpaCtrlEventMonitor,
WpaEventReadWrapper,
WpaFileReadRequest,
WpaStatusReadWrapper,
WpaWrapperBackend,
)
DEFAULT_CTRL_EVENT_TIMEOUT_SECONDS = 0.5
@dataclass(slots=True)
class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
@ -44,6 +47,7 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
receive_command: str | None = None
receive_arguments: tuple[str, ...] | None = None
timeout_seconds: float | None = None
event_monitor: WpaCtrlEventMonitor | None = field(default=None, init=False, repr=False)
state_machine: ConnectionStateMachine = field(
default_factory=ConnectionStateMachine, init=False, repr=False
)
@ -53,19 +57,28 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
event_wrapper: WpaEventReadWrapper = field(init=False, repr=False)
def __post_init__(self) -> None:
if self.descriptor.channel is WpaSourceChannel.CTRL_IFACE:
if self.descriptor.channel in {
WpaSourceChannel.CTRL_IFACE,
WpaSourceChannel.CTRL_EVENT,
}:
if self.interface_name is None:
self.interface_name = str(
self.descriptor.details.get(
"interface_name", self.descriptor.identifier
)
)
if self.timeout_seconds is None:
self.timeout_seconds = self.descriptor.timeout_seconds
if (
self.descriptor.channel is WpaSourceChannel.CTRL_EVENT
and self.timeout_seconds is None
):
self.timeout_seconds = DEFAULT_CTRL_EVENT_TIMEOUT_SECONDS
if self.descriptor.channel is WpaSourceChannel.CTRL_IFACE:
if self.receive_command is None:
self.receive_command = self.descriptor.receive_command
if self.receive_arguments is None:
self.receive_arguments = self.descriptor.receive_arguments
if self.timeout_seconds is None:
self.timeout_seconds = self.descriptor.timeout_seconds
else:
if self.path is None:
details_path = self.descriptor.details.get("path")
@ -77,7 +90,7 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
if self.receive_command is None:
self.receive_command = "STATUS"
self.receive_command = str(self.receive_command).strip()
if not self.receive_command:
if self.descriptor.channel is WpaSourceChannel.CTRL_IFACE and not self.receive_command:
raise ConnectionConfigurationError("receive_command must not be empty")
if self.receive_arguments is None:
self.receive_arguments = ()
@ -92,20 +105,50 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
if self.is_alive():
return
self.state_machine.mark_connecting(source=self.descriptor.source_uri)
if self.descriptor.channel is WpaSourceChannel.CTRL_IFACE:
if self.descriptor.channel in {
WpaSourceChannel.CTRL_IFACE,
WpaSourceChannel.CTRL_EVENT,
}:
if self.interface_name is None or not self.interface_name.strip():
raise ConnectionConfigurationError(
"ctrl_iface connection requires an interface name"
self.state_machine.mark_failed(
source=self.descriptor.source_uri,
error="ConnectionConfigurationError",
)
raise ConnectionConfigurationError(
f"{self.descriptor.channel.value} connection requires an interface name"
)
if self.descriptor.channel is WpaSourceChannel.CTRL_EVENT:
try:
self.event_monitor = self.backend.open_ctrl_event_monitor(
self._resolve_interface_name(),
self.timeout_seconds,
)
except Exception as exc:
self.state_machine.mark_failed(
source=self.descriptor.source_uri,
error=type(exc).__name__,
)
raise ConnectionTransportError(
f"unable to attach ctrl_event monitor for {self._resolve_interface_name()!r}"
) from exc
else:
path = self._resolve_path()
if not path.exists():
self.state_machine.mark_failed(
source=self.descriptor.source_uri,
error="ConnectionTransportError",
)
raise ConnectionTransportError(
f"wpa source path does not exist: {path}"
)
self.state_machine.mark_connected(source=self.descriptor.source_uri)
def disconnect(self) -> None:
if self.event_monitor is not None:
try:
self.event_monitor.close()
finally:
self.event_monitor = None
if self.state_machine.state is ConnectionState.DISCONNECTED:
return
if self.state_machine.state is ConnectionState.CONNECTED:
@ -122,11 +165,15 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
self._ensure_connected()
received_at = datetime.now(UTC)
if self.descriptor.channel is WpaSourceChannel.CTRL_IFACE:
command = self.receive_command
arguments = self.receive_arguments
assert command is not None
assert arguments is not None
result = self.ctrl_wrapper.invoke(
WpaCtrlIfaceRequest(
interface_name=self._resolve_interface_name(),
command=self.receive_command,
arguments=self.receive_arguments,
command=command,
arguments=arguments,
timeout_seconds=self.timeout_seconds,
)
)
@ -138,6 +185,18 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
data,
received_at=received_at,
)
if self.descriptor.channel is WpaSourceChannel.CTRL_EVENT:
if self.event_monitor is None:
raise ConnectionStateError("ctrl_event monitor is not attached")
data = self.event_monitor.receive(self.timeout_seconds)
if data is None:
return None
return build_raw_message(
self.descriptor,
data,
received_at=received_at,
encoding="utf-8",
)
path = self._resolve_path()
if self.descriptor.channel is WpaSourceChannel.CONFIG:
result = self.config_wrapper.invoke(
@ -161,7 +220,9 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
def send(self, message: RawMessage) -> None:
self._ensure_connected()
if self.descriptor.channel is not WpaSourceChannel.CTRL_IFACE:
raise ConnectionStateError("file-backed wpa sources are receive-only")
raise ConnectionStateError(
"ctrl_event and file-backed wpa sources are receive-only"
)
command, arguments = self._extract_command(message.data)
result = self.ctrl_wrapper.invoke(
WpaCtrlIfaceRequest(
@ -181,9 +242,11 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
"identifier": self.descriptor.identifier,
"source_uri": self.descriptor.source_uri,
"interface_name": self.interface_name,
"ctrl_socket_dir": self.descriptor.details.get("ctrl_socket_dir"),
"path": (
str(self._resolve_path())
if self.descriptor.channel is not WpaSourceChannel.CTRL_IFACE
if self.descriptor.channel
not in {WpaSourceChannel.CTRL_IFACE, WpaSourceChannel.CTRL_EVENT}
else None
),
"timeout_seconds": self.timeout_seconds,

View File

@ -12,11 +12,14 @@ from typing import Any
from app.adapters.skeleton.model import CanonicalMessage, Envelope, Payload, RawMessage
DEFAULT_CTRL_SOCKET_DIR = "/var/run/wpa_supplicant"
class WpaSourceChannel(StrEnum):
"""Source channels used by the wpa_supplicant adapter."""
CTRL_IFACE = "ctrl_iface"
CTRL_EVENT = "ctrl_event"
CONFIG = "config"
STATUS = "status"
EVENT = "event"
@ -52,6 +55,7 @@ def ctrl_iface_descriptor(
interface_name: str,
/,
*,
ctrl_socket_dir: str = DEFAULT_CTRL_SOCKET_DIR,
receive_command: str = "STATUS",
receive_arguments: tuple[str, ...] = (),
timeout_seconds: float | None = None,
@ -65,6 +69,7 @@ def ctrl_iface_descriptor(
normalized_arguments = tuple(str(argument) for argument in receive_arguments)
details: dict[str, Any] = {
"interface_name": normalized,
"ctrl_socket_dir": str(Path(ctrl_socket_dir)),
"receive_command": normalized_command,
"receive_arguments": normalized_arguments,
}
@ -83,6 +88,35 @@ def ctrl_iface_descriptor(
)
def ctrl_event_descriptor(
interface_name: str,
/,
*,
ctrl_socket_dir: str = DEFAULT_CTRL_SOCKET_DIR,
timeout_seconds: float | None = None,
content_type: str = "text/plain",
payload_kind: str = "text",
) -> WpaSourceDescriptor:
"""Build a source descriptor for ctrl_event traffic."""
normalized = _normalize_identifier(interface_name)
details: dict[str, Any] = {
"interface_name": normalized,
"ctrl_socket_dir": str(Path(ctrl_socket_dir)),
}
if timeout_seconds is not None:
details["timeout_seconds"] = timeout_seconds
return WpaSourceDescriptor(
channel=WpaSourceChannel.CTRL_EVENT,
identifier=normalized,
source_uri=f"wpa_supplicant://ctrl_event/{normalized}",
content_type=content_type,
payload_kind=payload_kind,
timeout_seconds=timeout_seconds,
details=details,
)
def file_descriptor(
channel: WpaSourceChannel,
path: str | Path,
@ -93,8 +127,8 @@ def file_descriptor(
) -> WpaSourceDescriptor:
"""Build a source descriptor for file-based wpa_supplicant reads."""
if channel is WpaSourceChannel.CTRL_IFACE:
raise ValueError("file_descriptor cannot use ctrl_iface channel")
if channel in {WpaSourceChannel.CTRL_IFACE, WpaSourceChannel.CTRL_EVENT}:
raise ValueError("file_descriptor cannot use ctrl channel")
normalized = _normalize_identifier(str(path))
return WpaSourceDescriptor(
channel=channel,
@ -212,6 +246,8 @@ __all__ = [
"build_envelope",
"build_payload",
"build_raw_message",
"DEFAULT_CTRL_SOCKET_DIR",
"ctrl_iface_descriptor",
"ctrl_event_descriptor",
"file_descriptor",
]

View File

@ -58,6 +58,14 @@ def _build_event_parser(
return WpaEventTextParser()
def _build_ctrl_event_parser(
descriptor: WpaSourceDescriptor,
/,
**kwargs: Any,
) -> WpaEventTextParser:
return WpaEventTextParser()
@dataclass(slots=True, frozen=True)
class WpaParserRegistry:
"""Immutable registry of WPA parser builders."""
@ -104,6 +112,10 @@ def default_wpa_parser_registry() -> WpaParserRegistry:
WpaSourceChannel.CTRL_IFACE,
_build_ctrl_iface_parser,
)
registry = registry.register_builder(
WpaSourceChannel.CTRL_EVENT,
_build_ctrl_event_parser,
)
registry = registry.register_builder(WpaSourceChannel.CONFIG, _build_config_parser)
registry = registry.register_builder(WpaSourceChannel.STATUS, _build_status_parser)
registry = registry.register_builder(WpaSourceChannel.EVENT, _build_event_parser)

View File

@ -3,6 +3,7 @@
from .contracts import (
WpaCtrlIfaceRequest,
WpaCtrlIfaceResult,
WpaCtrlEventMonitor,
WpaFileReadRequest,
WpaFileReadResult,
WpaWrapperBackend,
@ -25,6 +26,7 @@ __all__ = [
"WpaConfigReadWrapper",
"WpaCtrlIfaceRequest",
"WpaCtrlIfaceResult",
"WpaCtrlEventMonitor",
"WpaCtrlIfaceWrapper",
"WpaEventReadWrapper",
"WpaEventReceiveWrapper",

View File

@ -45,6 +45,21 @@ class WpaWrapperBackend(Protocol):
timeout_seconds: float | None = None,
) -> str: ...
def open_ctrl_event_monitor(
self,
interface_name: str,
timeout_seconds: float | None = None,
) -> WpaCtrlEventMonitor: ...
@runtime_checkable
class WpaCtrlEventMonitor(Protocol):
"""Event-monitor contract used for ctrl_event subscriptions."""
def receive(self, timeout_seconds: float | None = None) -> str | None: ...
def close(self) -> None: ...
@dataclass(slots=True, frozen=True)
class WpaCtrlIfaceRequest:
@ -128,6 +143,7 @@ def _freeze_mapping(value: Mapping[str, Any]) -> Mapping[str, Any]:
__all__ = [
"WpaCtrlIfaceRequest",
"WpaCtrlIfaceResult",
"WpaCtrlEventMonitor",
"WpaFileReadRequest",
"WpaFileReadResult",
"WpaWrapperBackend",

View File

@ -14,7 +14,10 @@ from app.adapters.skeleton.config import (
UniversalAdapterConfig,
UniversalAdapterConfigLoader,
)
from app.adapters.wpa_supplicant_adapter.model import WpaSourceChannel
from app.adapters.wpa_supplicant_adapter.model import (
DEFAULT_CTRL_SOCKET_DIR,
WpaSourceChannel,
)
from .models import (
AdapterKind,
@ -411,6 +414,7 @@ class ApplicationConfigLoader:
"channel",
"path",
"interface_name",
"ctrl_socket_dir",
"content_type",
"payload_kind",
"receive_command",
@ -427,14 +431,33 @@ class ApplicationConfigLoader:
raise ApplicationConfigFormatError(
f"adapters[{index}].wpa_source.receive_arguments must be a sequence"
)
channel = self._enum(
section.get("channel", WpaSourceChannel.STATUS),
WpaSourceChannel,
f"adapters[{index}].wpa_source.channel",
)
interface_name = self._optional_str(
section.get("interface_name"),
f"adapters[{index}].wpa_source.interface_name",
)
if channel in {WpaSourceChannel.CTRL_IFACE, WpaSourceChannel.CTRL_EVENT}:
if interface_name is None:
raise ApplicationConfigFormatError(
f"adapters[{index}].wpa_source.interface_name must not be empty"
)
ctrl_socket_dir = self._optional_str(
section.get("ctrl_socket_dir", DEFAULT_CTRL_SOCKET_DIR),
f"adapters[{index}].wpa_source.ctrl_socket_dir",
)
return WpaSourceConfig(
channel=self._enum(
section.get("channel", WpaSourceChannel.STATUS),
WpaSourceChannel,
f"adapters[{index}].wpa_source.channel",
),
channel=channel,
path=str(section.get("path", "")),
interface_name=section.get("interface_name"),
interface_name=interface_name,
ctrl_socket_dir=(
DEFAULT_CTRL_SOCKET_DIR
if ctrl_socket_dir is None
else ctrl_socket_dir
),
content_type=str(section.get("content_type", "text/plain")),
payload_kind=str(section.get("payload_kind", "text")),
receive_command=str(section.get("receive_command", "STATUS")),

View File

@ -97,3 +97,13 @@ adapters:
path: .tmp/wpa_status.txt
content_type: text/plain
payload_kind: text
# Live control socket examples:
# ctrl_iface:
# channel: ctrl_iface
# interface_name: wlan0
# ctrl_socket_dir: /run/wpa_supplicant
#
# ctrl_event:
# channel: ctrl_event
# interface_name: wlan0
# ctrl_socket_dir: /run/wpa_supplicant

View File

@ -7,7 +7,10 @@ from enum import StrEnum
from typing import Any
from app.adapters.skeleton.config import TraceMode, UniversalAdapterConfig
from app.adapters.wpa_supplicant_adapter.model import WpaSourceChannel
from app.adapters.wpa_supplicant_adapter.model import (
DEFAULT_CTRL_SOCKET_DIR,
WpaSourceChannel,
)
class AdapterKind(StrEnum):
@ -100,6 +103,7 @@ class WpaSourceConfig:
channel: WpaSourceChannel = WpaSourceChannel.STATUS
path: str = ""
interface_name: str | None = None
ctrl_socket_dir: str = DEFAULT_CTRL_SOCKET_DIR
content_type: str = "text/plain"
payload_kind: str = "text"
receive_command: str = "STATUS"

View File

@ -22,8 +22,10 @@ from app.adapters.skeleton.runtime import UniversalAdapterRuntime
from app.adapters.wpa_supplicant_adapter.factory import (
create_wpa_supplicant_adapter_runtime,
)
from app.adapters.wpa_supplicant_adapter.backend import WpaUnixSocketBackend
from app.adapters.wpa_supplicant_adapter.model import (
WpaSourceChannel,
ctrl_event_descriptor,
ctrl_iface_descriptor,
file_descriptor,
)
@ -101,6 +103,23 @@ class ConfiguredWpaWrapperBackend(WpaWrapperBackend):
def read_path(self, path: str | Path, timeout_seconds: float | None = None) -> str:
return Path(path).read_text(encoding="utf-8")
def open_ctrl_event_monitor(
self,
interface_name: str,
timeout_seconds: float | None = None,
):
raise ApplicationConfigFormatError(
"ctrl_event requires a live unix-socket WPA backend"
)
def _default_wpa_backend_factory(source: WpaSourceConfig) -> WpaWrapperBackend:
if source.channel is WpaSourceChannel.CTRL_IFACE and (
source.ctrl_reply is not None or source.ctrl_reply_path is not None
):
return ConfiguredWpaWrapperBackend(source=source)
return WpaUnixSocketBackend(ctrl_socket_dir=source.ctrl_socket_dir)
def default_adapter_runtime_builders() -> dict[AdapterKind, AdapterRuntimeBuilder]:
"""Return the built-in runtime builders for the supported adapter kinds."""
@ -120,6 +139,7 @@ class ApplicationSupervisor:
dbus_backend_factory: (
Callable[[DbusConnectionConfig], DbusWrapperBackend | None] | None
) = None
wpa_backend_factory: Callable[[WpaSourceConfig], WpaWrapperBackend] | None = None
runtime_builders: Mapping[AdapterKind, AdapterRuntimeBuilder] = field(
default_factory=default_adapter_runtime_builders
)
@ -330,6 +350,13 @@ class ApplicationSupervisor:
export_port,
backend_factory=self.dbus_backend_factory,
)
if adapter.kind is AdapterKind.WPA_SUPPLICANT and builder is _build_wpa_runtime:
wpa_builder = cast(Callable[..., UniversalAdapterRuntime], builder)
return wpa_builder(
adapter,
export_port,
backend_factory=self.wpa_backend_factory,
)
return builder(adapter, export_port)
def _worker_loop(self, worker: WorkerState) -> None:
@ -375,6 +402,7 @@ class ApplicationSupervisorBuilder:
dbus_backend_factory: (
Callable[[DbusConnectionConfig], DbusWrapperBackend | None] | None
) = None
wpa_backend_factory: Callable[[WpaSourceConfig], WpaWrapperBackend] | None = None
runtime_builders: Mapping[AdapterKind, AdapterRuntimeBuilder] = field(
default_factory=default_adapter_runtime_builders
)
@ -384,6 +412,7 @@ class ApplicationSupervisorBuilder:
return ApplicationSupervisor(
config=config,
dbus_backend_factory=self.dbus_backend_factory,
wpa_backend_factory=self.wpa_backend_factory,
runtime_builders=self.runtime_builders,
stream=self.stream,
)
@ -419,13 +448,19 @@ def _build_dbus_runtime(
def _build_wpa_runtime(
config: ApplicationAdapterConfig,
export_port: MessageExportPort,
*,
backend_factory: Callable[[WpaSourceConfig], WpaWrapperBackend] | None = None,
) -> UniversalAdapterRuntime:
if config.wpa_source is None:
raise ApplicationConfigFormatError(
"wpa_supplicant adapters require a wpa_source section"
)
source = config.wpa_source
backend = ConfiguredWpaWrapperBackend(source=source)
backend = (
_default_wpa_backend_factory(source)
if backend_factory is None
else backend_factory(source)
)
if source.channel is WpaSourceChannel.CTRL_IFACE:
if source.interface_name is None or not source.interface_name.strip():
raise ApplicationConfigFormatError(
@ -433,9 +468,19 @@ def _build_wpa_runtime(
)
descriptor = ctrl_iface_descriptor(
source.interface_name,
ctrl_socket_dir=source.ctrl_socket_dir,
receive_command=source.receive_command,
receive_arguments=source.receive_arguments,
)
elif source.channel is WpaSourceChannel.CTRL_EVENT:
if source.interface_name is None or not source.interface_name.strip():
raise ApplicationConfigFormatError(
"wpa_source.interface_name is required for ctrl_event adapters"
)
descriptor = ctrl_event_descriptor(
source.interface_name,
ctrl_socket_dir=source.ctrl_socket_dir,
)
else:
if not source.path.strip():
raise ApplicationConfigFormatError(

View File

@ -192,6 +192,62 @@ def test_multi_adapter_config_loads_mixed_kinds() -> None:
assert len(config.adapters[2].dbus_source.scan_profile.bands) == 2
def test_multi_adapter_config_loads_wpa_ctrl_event_source() -> None:
config = ApplicationConfigLoader().load_text(
dedent(
"""
adapters:
- kind: wpa_supplicant
config:
adapter:
adapter_id: wpa-event
connection:
type: file
file:
path: .tmp/wpa_event.log
acquisition:
trigger:
kind: poll
interval_seconds: 1
run_immediately: true
detection:
kind: blind
fetch:
kind: single
progress:
kind: none
parsing:
kind: text
validation:
mode: stub
prefilter:
mode: stub
marking:
mode: stub
export:
mode: bridge
commands:
mode: stub
observability:
sink: in_memory
wrapper:
path: ""
wpa_source:
channel: ctrl_event
interface_name: wlan0
ctrl_socket_dir: /run/wpa_supplicant
"""
)
)
assert len(config.adapters) == 1
source = config.adapters[0].wpa_source
assert source is not None
assert source.channel.value == "ctrl_event"
assert source.interface_name == "wlan0"
assert source.ctrl_socket_dir == "/run/wpa_supplicant"
def test_multi_adapter_config_rejects_invalid_kind() -> None:
with pytest.raises(ApplicationConfigFormatError):
ApplicationConfigLoader().load_text(

View File

@ -38,6 +38,7 @@ from app.application.models import (
WpaSourceConfig,
)
from app.application.supervisor import AdapterRuntimeBuilder, ApplicationSupervisor
from app.adapters.wpa_supplicant_adapter.model import WpaSourceChannel
from app.shared.contracts import MessageExportPort
from app.shared.contracts.proto.v1 import canonical_message_to_proto
@ -290,6 +291,69 @@ def test_supervisor_forwards_dbus_backend_factory_to_default_builder(monkeypatch
assert captured["backend_factory"] is backend_factory
def test_supervisor_forwards_wpa_backend_factory_to_default_builder(monkeypatch):
captured: dict[str, object] = {}
def fake_create_wpa_adapter_runtime(
config,
/,
*,
source_descriptor=None,
backend=None,
export_port,
**kwargs,
):
captured["backend"] = backend
class _Runtime:
def start(self) -> None:
return None
def stop(self) -> None:
return None
def run_once(self) -> int:
return 0
return _Runtime()
monkeypatch.setattr(
"app.application.supervisor.create_wpa_supplicant_adapter_runtime",
fake_create_wpa_adapter_runtime,
)
expected_backend = object()
def backend_factory(source):
return expected_backend
config = ApplicationConfig(
service=ServiceConfig(
name="wf-agent3",
director=DirectorKind.STDOUT_JSON,
join_timeout_seconds=0.5,
),
adapters=(
ApplicationAdapterConfig(
kind=AdapterKind.WPA_SUPPLICANT,
config=_runtime_config("wpa-adapter"),
wpa_source=WpaSourceConfig(
channel=WpaSourceChannel.CTRL_EVENT,
interface_name="wlan0",
),
),
),
)
supervisor = ApplicationSupervisor(
config=config,
wpa_backend_factory=backend_factory,
)
supervisor._build_runtime(config.adapters[0])
assert captured["backend"] is not None
assert captured["backend"] is expected_backend
def _noop_port() -> MessageExportPort:
class _Port(MessageExportPort):
def export(self, message: object) -> None:

View File

@ -451,9 +451,10 @@ def test_dbus_scan_snapshot_strategy_survives_optional_bss_property_failure() ->
backend.bss_properties[
"/fi/w1/wpa_supplicant1/Interfaces/1/BSSs/1"
]["BSSID"] = bytes.fromhex("aa bb cc dd ee 02")
backend.bss_properties[
"/fi/w1/wpa_supplicant1/Interfaces/1/BSSs/2"
]["SSID"] = "other-net"
backend.bss_properties.setdefault(
"/fi/w1/wpa_supplicant1/Interfaces/1/BSSs/2",
{},
)["SSID"] = "other-net"
backend.bss_property_failures.add(
("/fi/w1/wpa_supplicant1/Interfaces/1/BSSs/1", "Signal")
)
@ -485,9 +486,10 @@ def test_dbus_scan_snapshot_strategy_emits_empty_snapshot_when_all_bss_are_filte
"/fi/w1/wpa_supplicant1/Interfaces/1/BSSs/9",
]
)
backend.bss_properties[
"/fi/w1/wpa_supplicant1/Interfaces/1/BSSs/9"
]["SSID"] = "other-net"
backend.bss_properties.setdefault(
"/fi/w1/wpa_supplicant1/Interfaces/1/BSSs/9",
{},
)["SSID"] = "other-net"
driver = DBusConnectionDriver(
_dbus_config(),
backend=backend,

View File

@ -10,6 +10,7 @@ import pytest
from app.adapters.wpa_supplicant_adapter.acquisition import (
WpaConfigReadStrategy,
WpaCtrlIfaceAcquisitionStrategy,
WpaCtrlEventReceiveStrategy,
WpaEventReceiveStrategy,
WpaStatusPollingStrategy,
WpaSupplicantAcquisitionConfigurationError,
@ -19,17 +20,34 @@ from app.adapters.wpa_supplicant_adapter.connection import (
)
from app.adapters.wpa_supplicant_adapter.model import (
WpaSourceChannel,
ctrl_event_descriptor,
ctrl_iface_descriptor,
file_descriptor,
)
@dataclass
class FakeWpaEventMonitor:
events: list[str]
receive_calls: list[float | None] = field(default_factory=list)
def receive(self, timeout_seconds: float | None = None) -> str | None:
self.receive_calls.append(timeout_seconds)
if self.events:
return self.events.pop(0)
return None
def close(self) -> None:
return None
@dataclass
class FakeWpaBackend:
ctrl_calls: list[tuple[str, str, tuple[str, ...], float | None]] = field(
default_factory=list
)
read_calls: list[tuple[str, float | None]] = field(default_factory=list)
event_monitor: FakeWpaEventMonitor | None = None
def ctrl_request(
self,
@ -46,6 +64,17 @@ class FakeWpaBackend:
self.read_calls.append((str(path), timeout_seconds))
return path.read_text(encoding="utf-8")
def open_ctrl_event_monitor(
self,
interface_name: str,
timeout_seconds: float | None = None,
) -> FakeWpaEventMonitor:
if self.event_monitor is None:
self.event_monitor = FakeWpaEventMonitor(
events=["CTRL-EVENT-CONNECTED\n"]
)
return self.event_monitor
def test_ctrl_iface_acquisition_strategy_reads_once() -> None:
driver = WpaSupplicantConnectionDriver(
@ -60,6 +89,21 @@ def test_ctrl_iface_acquisition_strategy_reads_once() -> None:
assert messages[0].source == driver.descriptor.source_uri
def test_ctrl_event_acquisition_strategy_reads_once() -> None:
backend = FakeWpaBackend()
driver = WpaSupplicantConnectionDriver(
descriptor=ctrl_event_descriptor("wlan0"),
backend=backend,
)
driver.connect()
messages = list(WpaCtrlEventReceiveStrategy().acquire(driver))
assert len(messages) == 1
assert messages[0].source == driver.descriptor.source_uri
driver.disconnect()
def test_file_acquisition_strategies_read_expected_channels(tmp_path: Path) -> None:
status_path = tmp_path / "status.txt"
event_path = tmp_path / "events.log"

View File

@ -0,0 +1,129 @@
"""Tests for the real wpa_supplicant unix-socket backend."""
from __future__ import annotations
import socket
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
import pytest
from app.adapters.wpa_supplicant_adapter.backend import WpaUnixSocketBackend
AF_UNIX = getattr(socket, "AF_UNIX", None)
pytestmark = pytest.mark.skipif(
AF_UNIX is None, reason="AF_UNIX sockets are unavailable"
)
@dataclass
class WpaCtrlSocketFixture:
socket_path: Path
status_reply: bytes = b"wpa_state=COMPLETED\nssid=demo\n"
event_reply: bytes = b"CTRL-EVENT-CONNECTED\n"
server_socket: socket.socket | None = field(default=None, init=False)
thread: threading.Thread | None = field(default=None, init=False)
ready: threading.Event = field(default_factory=threading.Event, init=False)
stop_event: threading.Event = field(default_factory=threading.Event, init=False)
received_texts: list[str] = field(default_factory=list, init=False)
attached_client: str | None = field(default=None, init=False)
detached: bool = field(default=False, init=False)
def start(self) -> None:
self.socket_path.parent.mkdir(parents=True, exist_ok=True)
if self.socket_path.exists():
self.socket_path.unlink()
assert AF_UNIX is not None
self.server_socket = socket.socket(AF_UNIX, socket.SOCK_DGRAM)
self.server_socket.bind(str(self.socket_path))
self.server_socket.settimeout(0.2)
self.thread = threading.Thread(target=self._serve, daemon=True)
self.thread.start()
assert self.ready.wait(2.0)
def stop(self) -> None:
self.stop_event.set()
if self.server_socket is not None:
try:
self.server_socket.close()
finally:
self.server_socket = None
if self.thread is not None:
self.thread.join(timeout=2.0)
if self.socket_path.exists():
self.socket_path.unlink()
def send_event(self, payload: bytes | str) -> None:
if self.server_socket is None or self.attached_client is None:
raise AssertionError("ctrl_event monitor is not attached")
data = payload.encode("utf-8") if isinstance(payload, str) else payload
self.server_socket.sendto(data, self.attached_client)
def _serve(self) -> None:
assert self.server_socket is not None
self.ready.set()
while not self.stop_event.is_set():
try:
payload, addr = self.server_socket.recvfrom(65536)
except TimeoutError:
continue
except OSError:
if self.stop_event.is_set():
return
continue
text = payload.decode("utf-8", errors="replace")
self.received_texts.append(text)
if text == "STATUS":
self._reply(addr, self.status_reply)
elif text == "PING":
self._reply(addr, b"OK\n")
elif text == "ATTACH":
self.attached_client = addr
self._reply(addr, b"OK\n")
elif text == "DETACH":
self.detached = True
self._reply(addr, b"OK\n")
def _reply(self, addr: str, payload: bytes) -> None:
assert self.server_socket is not None
try:
self.server_socket.sendto(payload, addr)
except OSError:
pass
def test_ctrl_request_opens_expected_socket_path_and_sends_command(tmp_path: Path) -> None:
socket_dir = tmp_path / "wpa_supplicant"
fixture = WpaCtrlSocketFixture(socket_dir / "wlan0")
fixture.start()
backend = WpaUnixSocketBackend(ctrl_socket_dir=str(socket_dir))
reply = backend.ctrl_request("wlan0", "STATUS", ())
fixture.stop()
assert reply == "wpa_state=COMPLETED\nssid=demo\n"
assert fixture.received_texts == ["STATUS"]
def test_ctrl_event_monitor_attaches_receives_and_detaches(tmp_path: Path) -> None:
socket_dir = tmp_path / "wpa_supplicant"
fixture = WpaCtrlSocketFixture(socket_dir / "wlan0")
fixture.start()
backend = WpaUnixSocketBackend(ctrl_socket_dir=str(socket_dir))
monitor = backend.open_ctrl_event_monitor("wlan0", timeout_seconds=1.0)
fixture.send_event("CTRL-EVENT-CONNECTED\n")
event = monitor.receive(timeout_seconds=1.0)
monitor.close()
deadline = time.time() + 2.0
while time.time() < deadline and not fixture.detached:
time.sleep(0.05)
fixture.stop()
assert event == "CTRL-EVENT-CONNECTED\n"
assert "ATTACH" in fixture.received_texts
assert fixture.detached is True

View File

@ -14,17 +14,35 @@ from app.adapters.wpa_supplicant_adapter.connection import (
)
from app.adapters.wpa_supplicant_adapter.model import (
WpaSourceChannel,
ctrl_event_descriptor,
ctrl_iface_descriptor,
file_descriptor,
)
@dataclass
class FakeWpaEventMonitor:
events: list[str]
receive_calls: list[float | None] = field(default_factory=list)
close_calls: int = 0
def receive(self, timeout_seconds: float | None = None) -> str | None:
self.receive_calls.append(timeout_seconds)
if self.events:
return self.events.pop(0)
return None
def close(self) -> None:
self.close_calls += 1
@dataclass
class FakeWpaBackend:
ctrl_calls: list[tuple[str, str, tuple[str, ...], float | None]] = field(
default_factory=list
)
read_calls: list[tuple[str, float | None]] = field(default_factory=list)
event_monitor: FakeWpaEventMonitor | None = None
def ctrl_request(
self,
@ -49,6 +67,17 @@ class FakeWpaBackend:
self.read_calls.append((str(path), timeout_seconds))
return path.read_text(encoding="utf-8")
def open_ctrl_event_monitor(
self,
interface_name: str,
timeout_seconds: float | None = None,
) -> FakeWpaEventMonitor:
if self.event_monitor is None:
self.event_monitor = FakeWpaEventMonitor(
events=["CTRL-EVENT-CONNECTED\n", "CTRL-EVENT-DISCONNECTED\n"]
)
return self.event_monitor
def test_ctrl_iface_connection_driver_roundtrip() -> None:
backend = FakeWpaBackend()
@ -99,6 +128,29 @@ def test_ctrl_iface_connection_driver_uses_descriptor_metadata() -> None:
assert driver.transport_metadata()["receive_arguments"] == ("fast", "verbose")
def test_ctrl_event_connection_driver_reads_from_event_monitor() -> None:
backend = FakeWpaBackend()
driver = WpaSupplicantConnectionDriver(
descriptor=ctrl_event_descriptor("wlan0"),
backend=backend,
)
driver.connect()
raw = driver.receive()
second = driver.receive()
assert raw is not None
assert raw.source == "wpa_supplicant://ctrl_event/wlan0"
assert raw.data == "CTRL-EVENT-CONNECTED\n"
assert second is not None
assert second.data == "CTRL-EVENT-DISCONNECTED\n"
assert backend.event_monitor is not None
assert backend.event_monitor.receive_calls == [0.5, 0.5]
driver.disconnect()
assert backend.event_monitor.close_calls == 1
def test_ctrl_iface_connection_driver_explicit_values_override_descriptor_metadata() -> None:
backend = FakeWpaBackend()
driver = WpaSupplicantConnectionDriver(

View File

@ -13,6 +13,7 @@ from app.adapters.wpa_supplicant_adapter.factory import (
)
from app.adapters.wpa_supplicant_adapter.model import (
WpaSourceChannel,
ctrl_event_descriptor,
ctrl_iface_descriptor,
file_descriptor,
)
@ -23,12 +24,29 @@ from app.shared.observability import (
)
@dataclass
class FakeWpaEventMonitor:
events: list[str]
receive_calls: list[float | None] = field(default_factory=list)
close_calls: int = 0
def receive(self, timeout_seconds: float | None = None) -> str | None:
self.receive_calls.append(timeout_seconds)
if self.events:
return self.events.pop(0)
return None
def close(self) -> None:
self.close_calls += 1
@dataclass
class FakeWpaBackend:
ctrl_calls: list[tuple[str, str, tuple[str, ...], float | None]] = field(
default_factory=list
)
read_calls: list[tuple[str, float | None]] = field(default_factory=list)
event_monitor: FakeWpaEventMonitor | None = None
def ctrl_request(
self,
@ -53,6 +71,17 @@ class FakeWpaBackend:
self.read_calls.append((str(path), timeout_seconds))
return path.read_text(encoding="utf-8")
def open_ctrl_event_monitor(
self,
interface_name: str,
timeout_seconds: float | None = None,
) -> FakeWpaEventMonitor:
if self.event_monitor is None:
self.event_monitor = FakeWpaEventMonitor(
events=["CTRL-EVENT-CONNECTED\n"]
)
return self.event_monitor
def _build_config(adapter_id: str) -> UniversalAdapterConfig:
return UniversalAdapterConfig(adapter=AdapterSectionConfig(adapter_id=adapter_id))
@ -97,6 +126,7 @@ def test_ctrl_iface_factory_runs_end_to_end_with_descriptor_metadata() -> None:
assert snapshot.connection_state == "CONNECTED"
assert observability.counters["messages_in_total"] == 1
assert observability.counters["messages_out_total"] == 1
runtime.stop()
def test_status_file_factory_runs_end_to_end(tmp_path: Path) -> None:
@ -142,9 +172,44 @@ def test_status_file_factory_runs_end_to_end(tmp_path: Path) -> None:
assert snapshot.connection_state == "CONNECTED"
assert observability.counters["messages_in_total"] == 1
assert observability.counters["messages_out_total"] == 1
assert any(trace.action == "received" for trace in observability.traces)
assert any(trace.action == "parsed" for trace in observability.traces)
assert any(trace.action == "exported" for trace in observability.traces)
def test_ctrl_event_factory_runs_end_to_end() -> None:
backend = FakeWpaBackend()
stream = StringIO()
observability = InMemoryObservabilityService(
status_builder=StatusSnapshotBuilder(adapter_id="wpa-ctrl-event")
)
descriptor = ctrl_event_descriptor("wlan0")
factory = WpaSupplicantAdapterFactory(
source_descriptor=descriptor,
backend=backend,
export_port=StdoutJsonMessageDirector(stream=stream),
observability=observability,
)
runtime = factory.create(_build_config("wpa-ctrl-event"))
runtime.start()
handled = runtime.run_once()
assert handled == 1
assert backend.event_monitor is not None
assert backend.event_monitor.receive_calls == [0.5]
payload = json.loads(stream.getvalue().strip())
assert payload["envelope"]["source"] == descriptor.source_uri
assert payload["payload"]["data"] == "CTRL-EVENT-CONNECTED"
assert payload["meta"]["channel"] == "ctrl_event"
assert payload["meta"]["parser"] == "event"
assert payload["meta"]["payload_kind"] == "text"
assert payload["meta"]["transport"] == "wpa_supplicant"
snapshot = observability.snapshot()
assert snapshot.adapter_id == "wpa-ctrl-event"
assert snapshot.state == "RUNNING"
assert snapshot.connection_state == "CONNECTED"
assert observability.counters["messages_in_total"] == 1
assert observability.counters["messages_out_total"] == 1
def test_event_file_factory_runs_end_to_end(tmp_path: Path) -> None:

View File

@ -7,6 +7,7 @@ from datetime import UTC, datetime
from app.adapters.skeleton.model import RawMessage
from app.adapters.wpa_supplicant_adapter.model import (
WpaSourceChannel,
ctrl_event_descriptor,
ctrl_iface_descriptor,
file_descriptor,
)
@ -65,6 +66,21 @@ def test_event_parser_preserves_event_text() -> None:
assert message.meta["payload_kind"] == "text"
def test_ctrl_event_parser_preserves_event_text() -> None:
descriptor = ctrl_event_descriptor("wlan0")
raw = RawMessage(
data="CTRL-EVENT-CONNECTED\n",
source=descriptor.source_uri,
transport="wpa_supplicant",
)
message = WpaEventTextParser().parse(raw)
assert message.payload.data == "CTRL-EVENT-CONNECTED"
assert message.meta["channel"] == WpaSourceChannel.CTRL_EVENT.value
assert message.meta["payload_kind"] == "text"
def test_config_parser_preserves_text_payload() -> None:
descriptor = file_descriptor(WpaSourceChannel.CONFIG, "/var/run/wpa/wpa.conf")
raw = RawMessage(

View File

@ -6,11 +6,13 @@ from datetime import UTC, datetime
from app.adapters.skeleton.model import WrapperCallContext
from app.adapters.wpa_supplicant_adapter.model import (
DEFAULT_CTRL_SOCKET_DIR,
WpaSourceChannel,
build_canonical_message,
build_envelope,
build_payload,
build_raw_message,
ctrl_event_descriptor,
ctrl_iface_descriptor,
file_descriptor,
)
@ -28,6 +30,7 @@ from app.adapters.wpa_supplicant_adapter.wrappers import (
def test_ctrl_iface_source_mapping_builds_canonical_message() -> None:
descriptor = ctrl_iface_descriptor(
"wlan0",
ctrl_socket_dir="/run/wpa_supplicant",
receive_command="PING",
receive_arguments=("reconfigure", "wlan0"),
timeout_seconds=1.5,
@ -53,6 +56,7 @@ def test_ctrl_iface_source_mapping_builds_canonical_message() -> None:
assert descriptor.receive_command == "PING"
assert descriptor.receive_arguments == ("reconfigure", "wlan0")
assert descriptor.timeout_seconds == 1.5
assert descriptor.details["ctrl_socket_dir"] == "/run/wpa_supplicant"
assert descriptor.details["receive_command"] == "PING"
assert raw.source == descriptor.source_uri
assert raw.transport == "wpa_supplicant"
@ -64,6 +68,21 @@ def test_ctrl_iface_source_mapping_builds_canonical_message() -> None:
assert message.meta["channel"] == WpaSourceChannel.CTRL_IFACE.value
def test_ctrl_event_source_mapping_builds_canonical_message() -> None:
descriptor = ctrl_event_descriptor("wlan0", timeout_seconds=2.0)
message = build_canonical_message(
descriptor,
"CTRL-EVENT-CONNECTED\n",
encoding="utf-8",
)
assert descriptor.channel is WpaSourceChannel.CTRL_EVENT
assert descriptor.source_uri == "wpa_supplicant://ctrl_event/wlan0"
assert descriptor.details["ctrl_socket_dir"] == DEFAULT_CTRL_SOCKET_DIR
assert descriptor.timeout_seconds == 2.0
assert message.meta["channel"] == WpaSourceChannel.CTRL_EVENT.value
def test_file_source_mapping_uses_file_channels() -> None:
descriptor = file_descriptor(
WpaSourceChannel.STATUS,