Проект разделён по каталогам agent и backend. Поддержка legacy messages удалена

This commit is contained in:
Ilgiz Kamelyev 2026-05-04 10:31:02 +05:00
parent 1e457871fa
commit b5f1c067ff
54 changed files with 652 additions and 366 deletions

185
README.md
View File

@ -1,174 +1,69 @@
# rb-wf-ag
# wfagent Monorepo
Wi-Fi event/command bridge for `wpa_supplicant`.
This repository contains two independent Python applications:
The application:
- [`agent/`](./agent) - the `wfagent` agent for `wpa_supplicant`
- [`backend/`](./backend) - the `wfagent_backend` HTTP delivery backend
- reads events from D-Bus, `ctrl_iface`, and internal runtime sources
- applies source-specific filters before normalization
- classifies events into `drop`, `serialize_only`, or `serialize_and_trigger`
- writes selected events to `stdout` as NDJSON
- dispatches triggered commands to the explicitly configured destination
- keeps command execution status separate from returned destination data
Each application has its own `README.md`, `pyproject.toml`, tests, and example configuration.
## Layout
- [`agent/README.md`](./agent/README.md)
- [`agent/pyproject.toml`](./agent/pyproject.toml)
- [`agent/wfagent.example.yaml`](./agent/wfagent.example.yaml)
- [`backend/README.md`](./backend/README.md)
- [`backend/pyproject.toml`](./backend/pyproject.toml)
- [`backend/wfagent_backend.example.yaml`](./backend/wfagent_backend.example.yaml)
## Install
Install the agent:
```bash
cd agent
python -m pip install -e .
```
Install the backend:
```bash
cd backend
python -m pip install -e .
```
## Run
```bash
rb-wf-ag --config config.yaml
```
or:
Run the agent:
```bash
python -m rb_wf_ag --config config.yaml
cd agent
wfagent --config wfagent.example.yaml
```
## Configuration
The application expects a versioned YAML config. A minimal example:
```yaml
version: 1
runtime:
generate_events:
start: true
reload: true
stop: true
timer_tick: true
timers:
timer_tick_interval_ms: 100
sources:
dbus:
enabled: false
bus: system
service: fi.w1.wpa_supplicant1
root_path: /fi/w1/wpa_supplicant1
interface_name: fi.w1.wpa_supplicant1.Interface
filters: []
ctrl_iface:
enabled: true
socket_path: /var/run/wpa_supplicant/wlan0
attach_for_events: true
filters: []
runtime:
enabled: true
filters: []
classifier:
rules:
- id: serialize-runtime-start
enabled: true
match:
source_type: runtime
event_kind: start
disposition: serialize_only
triggers:
rules:
- id: on-start-request-status
enabled: true
match:
source_type: runtime
event_kind: start
command:
command_kind: get_status
destination: ctrl_iface
arguments: {}
cooldown_ms: 2000
max_retries: 0
commands:
dispatch:
strategy: explicit_destination_only
dbus:
enabled: true
methods:
get_interface:
object: fi.w1.wpa_supplicant1
method: GetInterface
ctrl_iface:
enabled: true
commands:
get_status: STATUS
output:
format: ndjson
target: stdout
flush_every_event: true
observability:
emit_internal_metrics: true
log_level: info
guards:
trigger_loop_guard:
default_cooldown_ms: 5000
dedup_window_ms: 3000
```
## NDJSON output
Each serialized event is a single JSON object per line. Example:
```json
{"event_id":"e-1001","source_type":"runtime","source_id":"runtime","event_kind":"start","observed_at_unix_ms":1760000000000,"severity":"info","payload":{"payload":{"state":"start"}}}
```
## Live smoke test
The repository includes a live integration smoke test for `ctrl_iface`.
Set one of these environment variables to the Unix socket path used by `wpa_supplicant`:
- `RB_WF_AG_CTRL_IFACE_SOCKET`
- `WPA_CTRL_IFACE_PATH`
Then run:
Run the backend:
```bash
pytest -m integration
cd backend
wfagent_backend --config wfagent_backend.example.yaml
```
The smoke test connects to the socket, issues `STATUS`, and checks that a state response is returned.
## Test
There is also a live D-Bus smoke test for `wpa_supplicant`.
Set this environment variable to the interface name managed by `wpa_supplicant`:
- `RB_WF_AG_DBUS_IFNAME`
Then run:
Run the agent tests:
```bash
pytest -m integration
pytest agent/tests
```
The D-Bus smoke test connects to the system bus, calls `GetInterface`, and checks that a proxy path is returned.
A second D-Bus smoke test exercises safe signal subscription on the main D-Bus object:
- `InterfaceAdded`
- `InterfaceRemoved`
- `PropertiesChanged`
It does not require a live signal to be emitted, only that the handlers can be subscribed successfully.
## Development
Run the normal test suite:
Run the backend tests:
```bash
pytest
pytest backend/tests
```
The default suite is self-contained and does not require a live `wpa_supplicant`.
## More Information
- Agent architecture and configuration: [`agent/README.md`](./agent/README.md)
- Backend architecture and configuration: [`backend/README.md`](./backend/README.md)
- Backend architecture notes: [`backend/wfagent_backend_architecture.md`](./backend/wfagent_backend_architecture.md)

350
agent/README.md Normal file
View File

@ -0,0 +1,350 @@
# wfagent
Wi-Fi event/command bridge for `wpa_supplicant` with a separate delivery backend.
This repository contains two installable Python applications:
- `wfagent`, the agent that reads events from `wpa_supplicant`, processes them, writes selected events to `stdout` as NDJSON, and can trigger commands.
- `wfagent_backend`, the HTTP backend that receives webhook deliveries from agents, normalizes them, queues them, and maps payload fields to downstream metrics.
The two applications are intentionally decoupled and can be deployed on different hosts.
## System Overview
The agent is the event producer and command orchestrator. It consumes:
- D-Bus events from the `wpa_supplicant` tree
- `ctrl_iface` unsolicited lines from the Unix socket
- internal runtime events such as `start`, `reload`, `stop`, and `timer_tick`
The agent then:
1. applies source-specific filters
2. normalizes the event into the internal model
3. classifies it as `drop`, `serialize_only`, or `serialize_and_trigger`
4. serializes selected events to `stdout` as NDJSON
5. creates command requests for trigger rules
6. dispatches commands to an explicitly configured destination
7. optionally delivers normalized event batches to the backend over HTTP
The backend is the delivery and persistence side. It:
1. accepts webhook requests on `POST /api/v1/ingest`
2. expects canonical `items[]` payloads only
3. normalizes requests into internal delivery objects
4. enqueues items for retry and batching
5. maps selected payload fields to downstream metric definitions
6. sends data through `zabbix_sender`
## Architecture
### Agent data flow
```text
DBus Source -----------\
\
Runtime Source ---------> Source Filters -> Normalizer -> Classifier -> NDJSON Serializer -> stdout
/ |
CtrlIface Source ------/ |
+--> Trigger Engine -> Command Dispatcher
|
+--> Delivery Service -> Backend
```
### Backend data flow
```text
HTTP ingest -> Request normalization -> Queue -> Mapper -> Sender
| |
| +-> zabbix_sender
+-> NDJSON response/log output
```
## Repository Structure
### Agent package
Located in [`src/wfagent`](./src/wfagent):
- [`cli.py`](./src/wfagent/cli.py) - agent CLI entry point
- [`config.py`](./src/wfagent/config.py) - YAML config loader and validators
- [`models.py`](./src/wfagent/models.py) - event, command, and delivery models
- [`sources.py`](./src/wfagent/sources.py) - D-Bus, `ctrl_iface`, and runtime sources
- [`pipeline.py`](./src/wfagent/pipeline.py) - filtering, normalization, classification, serialization, triggering
- [`commands.py`](./src/wfagent/commands.py) - command dispatching
- [`delivery/`](./src/wfagent/delivery) - webhook delivery, queue/spool, and backend integration
- [`lifecycle.py`](./src/wfagent/lifecycle.py) - runtime lifecycle handling
- [`services.py`](./src/wfagent/services.py) - clock, correlation IDs, observability
- [`payloads/`](./src/wfagent/payloads) - payload decoding helpers
### Backend package
Located in [`../backend/src/wfagent_backend`](../backend/src/wfagent_backend):
- [`cli.py`](../backend/src/wfagent_backend/cli.py) - backend CLI entry point
- [`config.py`](../backend/src/wfagent_backend/config.py) - backend config loader and validators
- [`app.py`](../backend/src/wfagent_backend/app.py) - request normalization and ingest handling
- [`server.py`](../backend/src/wfagent_backend/server.py) - HTTP server and routing
- [`queue.py`](../backend/src/wfagent_backend/queue.py) - in-memory queueing and retry coordination
- [`mapping.py`](../backend/src/wfagent_backend/mapping.py) - metric mapping logic
- [`sender.py`](../backend/src/wfagent_backend/sender.py) - `zabbix_sender` adapter
- [`contracts.py`](../backend/src/wfagent_backend/contracts.py) - ingest and delivery data models
## Agent Principles
The agent is designed around a single unified event pipeline:
- sources are transport-specific and lightweight
- source-specific filters run before normalization
- runtime events are first-class inputs
- classification decides whether an event is dropped, serialized, or also used for triggering
- stdout is the only serialization target for events in the agent
- command execution is separated from command result data
- every command request targets an explicit destination without fallback routing
### Supported event sources
- D-Bus:
- `fi.w1.wpa_supplicant1`
- `fi.w1.wpa_supplicant1.Interface`
- signals such as `InterfaceAdded`, `InterfaceRemoved`, and `PropertiesChanged`
- `ctrl_iface`:
- commands such as `STATUS`, `SCAN`, `SCAN_RESULTS`, `BSS`, `REASSOCIATE`, `RECONNECT`, and `TERMINATE`
- unsolicited events after `ATTACH`, for example `CTRL-EVENT-SCAN-RESULTS`
- runtime:
- `start`
- `reload`
- `stop`
- `timer_tick`
## Backend Principles
The backend is a separate HTTP service with a narrower job:
- accept deliveries from agents over HTTP
- validate and normalize canonical payload shapes
- keep deliveries in memory with retry and TTL policies
- map normalized payload fields to metric definitions
- send metrics via `zabbix_sender`
- emit structured NDJSON logging if enabled
The backend does not talk to `wpa_supplicant` directly.
## Configuration
Both applications use versioned YAML configuration.
### Agent configuration
The agent config is documented in [`wfagent.example.yaml`](./wfagent.example.yaml). The main sections are:
- `runtime` - runtime-generated events and timer interval
- `normalization` - payload parsing behavior
- `delivery` - webhook delivery settings for the backend
- `sources` - D-Bus, `ctrl_iface`, and runtime source settings
- `classifier` - event classification rules
- `triggers` - command trigger rules
- `commands` - explicit destination command definitions
- `output` - NDJSON serialization target
- `observability` - logging and metrics behavior
- `guards` - trigger loop and deduplication protection
Key deployment fields:
- `delivery.agent_id` - stable logical deployment name
- `delivery.agent_instance_id` - unique host/interface identity
- `delivery.webhook.url` - backend ingest URL
- `sources.ctrl_iface.socket_path` - `wpa_supplicant` control socket
- `sources.dbus.service` - D-Bus service name
### Backend configuration
The backend config is documented in [`../backend/wfagent_backend.example.yaml`](../backend/wfagent_backend.example.yaml). The main sections are:
- `server` - bind address, ingest path, health path, request limit
- `agent` - agent identity used in responses and logs
- `logging` - NDJSON logging toggle and log level
- `queue` - queue size, batch size, TTL, and retry policy
- `zabbix` - sender process and target host/port
- `mapping` - rules that turn event fields into metric samples
### Example agent config
The provided [`wfagent.example.yaml`](./wfagent.example.yaml) is a practical starting point for a single-host deployment. It enables:
- D-Bus source
- `ctrl_iface` source
- runtime source
- webhook delivery to the backend
### Example backend config
The provided [`../backend/wfagent_backend.example.yaml`](../backend/wfagent_backend.example.yaml) is a minimal backend instance that listens on:
```text
POST /api/v1/ingest
GET /healthz
```
and sends mapped metrics to `zabbix_sender`.
## Install
From the repository root:
```bash
cd agent
python -m pip install -e .
```
Install the backend from the backend project directory:
```bash
cd backend
python -m pip install -e .
```
## Run
### Agent
```bash
cd agent
wfagent --config wfagent.example.yaml
```
or:
```bash
cd agent
python -m wfagent --config wfagent.example.yaml
```
### Backend
```bash
cd backend
wfagent_backend --config wfagent_backend.example.yaml
```
Optional overrides:
```bash
wfagent_backend --config wfagent_backend.example.yaml --host 127.0.0.1 --port 8080
```
## Deployment
### Typical split deployment
1. Run `wfagent` from `agent/` on the host that has access to `wpa_supplicant`.
2. Run `wfagent_backend` from `backend/` on the destination host or on the same host.
3. Point `delivery.webhook.url` in the agent config at the backend ingest endpoint.
4. Keep `delivery.agent_id` stable across a logical fleet.
5. Set `delivery.agent_instance_id` per host or per wireless interface.
### Agent deployment notes
- Install the agent into a virtual environment.
- Make sure the user running the agent can access the D-Bus system bus and `wpa_supplicant` control socket.
- Prefer a dedicated `wpa_supplicant` interface socket path per interface, for example `/var/run/wpa_supplicant/wlp3s0`.
- Use `timer_tick_interval_ms` conservatively if triggers can cause command loops.
### Backend deployment notes
- Bind the backend to localhost if the agent runs on the same host.
- Put the backend behind a reverse proxy or private network if it is exposed remotely.
- Configure `zabbix_sender` access and credentials at the host level, not in the agent.
- Increase `queue.max_items` and `queue.item_ttl_ms` only if you expect backpressure.
## Data Format
### NDJSON output from the agent
Each serialized event is written as one JSON object per line.
Example:
```json
{"event_id":"e-1001","source_type":"runtime","source_id":"runtime","event_kind":"start","observed_at_unix_ms":1760000000000,"severity":"info","payload":{"payload":{"state":"start"}}}
```
### Backend ingest payloads
Canonical payload:
```json
{
"batch_id": "del-1",
"agent_id": "wfagent",
"agent_instance_id": "wfagent@wlp3s0",
"sent_at_unix_ms": 1760000000000,
"items": [
{
"item_id": "evt-1",
"item_kind": "event",
"source_type": "dbus",
"source_id": "fi.w1.wpa_supplicant1",
"event_kind": "properties_changed",
"observed_at_unix_ms": 1760000000000,
"target": {
"kind": "bss",
"value": "/fi/w1/wpa_supplicant1/Interfaces/0/BSSs/0"
},
"data_kind": "properties_changed",
"payload": {
"changed": {
"Signal": -41,
"Age": 0
}
}
}
]
}
```
## Examples
### Agent example
The agent directory includes [`wfagent.example.yaml`](./wfagent.example.yaml), which demonstrates:
- D-Bus source configuration
- `ctrl_iface` socket configuration
- runtime event generation
- classifier rules
- trigger rules
- webhook delivery to the backend
### Backend example
The backend directory includes [`../backend/wfagent_backend.example.yaml`](../backend/wfagent_backend.example.yaml), which demonstrates:
- HTTP server binding
- ingest path and health path
- queue and retry configuration
- Zabbix sender settings
- metric mapping from BSS event payloads
## Testing
Run the full test suite:
```bash
pytest
```
The default suite is self-contained and does not require a live `wpa_supplicant`.
### Integration tests
The repository also includes live smoke tests for `wpa_supplicant` integrations.
- D-Bus tests use the `WFAGENT_DBUS_IFNAME` environment variable.
- `ctrl_iface` tests use the `WFAGENT_CTRL_IFACE_SOCKET` or `WPA_CTRL_IFACE_PATH`.
Run them with:
```bash
pytest -m integration
```

View File

@ -3,7 +3,7 @@ requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "rb-wf-ag"
name = "wfagent"
version = "0.1.0"
description = "Wi-Fi event/command bridge for wpa_supplicant"
readme = "README.md"
@ -14,7 +14,7 @@ dependencies = [
]
[project.scripts]
rb-wf-ag = "rb_wf_ag.cli:main"
wfagent = "wfagent.cli:main"
[tool.setuptools]
package-dir = {"" = "src"}

View File

@ -55,7 +55,7 @@ def build_application(config: AppConfig) -> ApplicationRuntime:
clock=clock,
correlation_ids=correlation_ids,
observability=observability,
agent_id=config.delivery.agent_id or "rb-wf-ag",
agent_id=config.delivery.agent_id or "wfagent",
agent_instance_id=config.delivery.agent_instance_id,
)
@ -118,7 +118,7 @@ def build_application(config: AppConfig) -> ApplicationRuntime:
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="rb-wf-ag")
parser = argparse.ArgumentParser(prog="wfagent")
parser.add_argument("--config", required=True, help="Path to YAML configuration")
parser.add_argument("--log-level", default=None, help="Override log level")
return parser
@ -134,6 +134,6 @@ def main(argv: Sequence[str] | None = None) -> int:
try:
asyncio.run(runtime.run())
except OSError as exc:
print(f"rb-wf-ag: startup failed: {exc}", file=sys.stderr)
print(f"wfagent: startup failed: {exc}", file=sys.stderr)
return 1
return 0

View File

@ -70,7 +70,7 @@ class DeliveryService:
clock: Clock | None = None,
correlation_ids: CorrelationIdProvider | None = None,
observability: Observability | None = None,
agent_id: str = "rb-wf-ag",
agent_id: str = "wfagent",
agent_instance_id: str | None = None,
) -> None:
self._webhook_client = webhook_client

View File

@ -27,7 +27,7 @@ class Observability:
def _log(self) -> logging.Logger:
if self.logger is None:
self.logger = logging.getLogger("rb_wf_ag")
self.logger = logging.getLogger("wfagent")
return self.logger
def increment(self, metric_name: str, amount: int = 1) -> None:

View File

@ -3,10 +3,10 @@ from __future__ import annotations
from pathlib import Path
from textwrap import dedent
import rb_wf_ag.cli as cli
from rb_wf_ag.cli import build_application
from rb_wf_ag.config import load_app_config
from rb_wf_ag.pipeline import ApplicationRuntime
import wfagent.cli as cli
from wfagent.cli import build_application
from wfagent.config import load_app_config
from wfagent.pipeline import ApplicationRuntime
def test_build_application_creates_runtime(tmp_path: Path) -> None:

View File

@ -7,18 +7,18 @@ from dbus_next.constants import MessageType
from dbus_next.message import Message
from dbus_next.signature import Variant
from rb_wf_ag.commands import CommandDispatcher
from rb_wf_ag.commands import DbusCommandClient
from rb_wf_ag.commands import CtrlIfaceCommandClient
from rb_wf_ag.config import load_app_config
from rb_wf_ag.models import (
from wfagent.commands import CommandDispatcher
from wfagent.commands import DbusCommandClient
from wfagent.commands import CtrlIfaceCommandClient
from wfagent.config import load_app_config
from wfagent.models import (
CommandExecutionResult,
CommandEndpoint,
CommandRequest,
CommandResult,
CommandReturnedData,
)
from rb_wf_ag.sources import CtrlIfaceEventSource
from wfagent.sources import CtrlIfaceEventSource
class FakeCtrlIfaceClient:

View File

@ -5,7 +5,7 @@ from textwrap import dedent
import pytest
from rb_wf_ag.config import load_app_config
from wfagent.config import load_app_config
def _write_config(tmp_path: Path, text: str) -> Path:
@ -33,8 +33,8 @@ def test_load_app_config(tmp_path: Path) -> None:
delivery:
enabled: true
mode: webhook
agent_id: rb-wf-ag
agent_instance_id: rb-wf-ag@wlp3s0
agent_id: wfagent
agent_instance_id: wfagent@wlp3s0
webhook:
enabled: true
url: http://127.0.0.1:8080/api/ingest
@ -163,8 +163,8 @@ def test_load_app_config(tmp_path: Path) -> None:
assert config.normalization.payload_parsing.enabled is False
assert config.delivery.enabled is True
assert config.delivery.mode == "webhook"
assert config.delivery.agent_id == "rb-wf-ag"
assert config.delivery.agent_instance_id == "rb-wf-ag@wlp3s0"
assert config.delivery.agent_id == "wfagent"
assert config.delivery.agent_instance_id == "wfagent@wlp3s0"
assert config.delivery.webhook.enabled is True
assert config.delivery.webhook.url == "http://127.0.0.1:8080/api/ingest"
assert config.delivery.webhook.retry.max_attempts == 4
@ -443,7 +443,9 @@ def test_load_app_config_rejects_bad_version(tmp_path: Path) -> None:
def test_load_any_events_config_includes_dbus_properties_methods() -> None:
config = load_app_config(Path("config.any-events.yaml"))
config = load_app_config(
Path(__file__).resolve().parents[1] / "wfagent.example.yaml"
)
assert config.commands.dbus.methods["get_properties_root"].method == "GetAll"
assert config.commands.dbus.methods["get_properties_root"].properties_interface == "fi.w1.wpa_supplicant1"

View File

@ -4,7 +4,7 @@ import asyncio
import json
from typing import Any
from rb_wf_ag.delivery import (
from wfagent.delivery import (
DeliveryBatch,
DeliveryItem,
DeliveryResult,
@ -15,15 +15,15 @@ from rb_wf_ag.delivery import (
)
from _pytest.monkeypatch import MonkeyPatch
from rb_wf_ag.delivery import webhook as webhook_module
from rb_wf_ag.models import (
from wfagent.delivery import webhook as webhook_module
from wfagent.models import (
CommandExecutionResult,
CommandRequest,
CommandResult,
CommandReturnedData,
NormalizedEvent,
)
from rb_wf_ag.services import Clock
from wfagent.services import Clock
class MutableClock(Clock):
@ -173,15 +173,15 @@ def test_webhook_client_serializes_batch_and_attaches_headers(monkeypatch: Monke
timeout_ms=3000,
headers={
"Authorization": "Bearer token",
"X-Agent-Id": "rb-wf-ag-01",
"X-Agent-Id": "wfagent-01",
},
clock=Clock(),
)
batch = DeliveryBatch(
batch_id="del-1",
sent_at_unix_ms=1_700_000_000_000,
agent_id="rb-wf-ag",
agent_instance_id="rb-wf-ag@test",
agent_id="wfagent",
agent_instance_id="wfagent@test",
items=[
_delivery_item("evt-1", 1_700_000_000_000, 60_000),
_delivery_item("cmd-1", 1_700_000_000_000, 60_000, kind="command_result"),
@ -197,8 +197,8 @@ def test_webhook_client_serializes_batch_and_attaches_headers(monkeypatch: Monke
assert request.full_url == "http://127.0.0.1:8080/api/ingest"
body = json.loads(request.data.decode("utf-8"))
assert body["batch_id"] == "del-1"
assert body["agent_id"] == "rb-wf-ag"
assert body["agent_instance_id"] == "rb-wf-ag@test"
assert body["agent_id"] == "wfagent"
assert body["agent_instance_id"] == "wfagent@test"
assert body["sent_at_unix_ms"] == 1_700_000_000_000
assert len(body["items"]) == 2
assert body["items"][0]["item_kind"] == "event"
@ -231,8 +231,8 @@ def test_delivery_service_batches_events_and_retries_failed_batches() -> None:
retry_max_backoff_ms=50,
retry_multiplier=2.0,
clock=clock,
agent_id="rb-wf-ag",
agent_instance_id="rb-wf-ag@test",
agent_id="wfagent",
agent_instance_id="wfagent@test",
)
now = clock.now_unix_ms()
request, result = _command_result()
@ -253,8 +253,8 @@ def test_delivery_service_batches_events_and_retries_failed_batches() -> None:
assert len(client.batches) >= 2
first_batch = client.batches[0]
second_batch = client.batches[1]
assert first_batch.agent_id == "rb-wf-ag"
assert first_batch.agent_instance_id == "rb-wf-ag@test"
assert first_batch.agent_id == "wfagent"
assert first_batch.agent_instance_id == "wfagent@test"
assert "destination_url" not in first_batch.to_dict()
assert [item.item_kind for item in first_batch.items] == [
"event",

View File

@ -5,13 +5,13 @@ import os
import pytest
from rb_wf_ag.commands import DbusCommandClient
from rb_wf_ag.config import load_app_config
from rb_wf_ag.sources import DbusEventSource
from wfagent.commands import DbusCommandClient
from wfagent.config import load_app_config
from wfagent.sources import DbusEventSource
def _ifname() -> str | None:
value = os.environ.get("RB_WF_AG_DBUS_IFNAME") or os.environ.get("WPA_DBUS_IFNAME")
value = os.environ.get("WFAGENT_DBUS_IFNAME") or os.environ.get("WPA_DBUS_IFNAME")
if not value:
return None
value = value.strip()

View File

@ -5,11 +5,11 @@ from pathlib import Path
import pytest
from rb_wf_ag.commands import CtrlIfaceCommandClient
from wfagent.commands import CtrlIfaceCommandClient
def _socket_path() -> str | None:
candidate = os.environ.get("RB_WF_AG_CTRL_IFACE_SOCKET") or os.environ.get(
candidate = os.environ.get("WFAGENT_CTRL_IFACE_SOCKET") or os.environ.get(
"WPA_CTRL_IFACE_PATH"
)
if not candidate:

View File

@ -1,9 +1,9 @@
from __future__ import annotations
from rb_wf_ag.payloads.contracts import BlobDecodeContext
from rb_wf_ag.payloads.decoders.field_values import FieldValueBlobDecoder
from rb_wf_ag.payloads.decoders.wps_wfd import WfdIeBlobDecoder, WpsIeBlobDecoder
from rb_wf_ag.payloads.decoders.tlv import TlvBlobDecoder
from wfagent.payloads.contracts import BlobDecodeContext
from wfagent.payloads.decoders.field_values import FieldValueBlobDecoder
from wfagent.payloads.decoders.wps_wfd import WfdIeBlobDecoder, WpsIeBlobDecoder
from wfagent.payloads.decoders.tlv import TlvBlobDecoder
def _context(field_name: str = "IEs") -> BlobDecodeContext:

View File

@ -11,7 +11,7 @@ from dbus_next.message import Message
from dbus_next.aio.message_bus import MessageBus
from dbus_next.signature import Variant
from rb_wf_ag.models import (
from wfagent.models import (
CommandExecutionResult,
CommandRequest,
CommandResult,
@ -23,7 +23,7 @@ from rb_wf_ag.models import (
SourceFilterRule,
TriggerRule,
)
from rb_wf_ag.pipeline import (
from wfagent.pipeline import (
ApplicationRuntime,
EventClassifier,
EventNormalizer,
@ -34,8 +34,8 @@ from rb_wf_ag.pipeline import (
TriggerEngine,
TriggerLoopGuard,
)
from rb_wf_ag.services import Clock, Observability
from rb_wf_ag.sources import DbusEventSource
from wfagent.services import Clock, Observability
from wfagent.sources import DbusEventSource
class FixedClock(Clock):
@ -1210,7 +1210,7 @@ def test_dbus_interface_removed_is_serialized_through_pipeline() -> None:
def test_command_results_are_logged() -> None:
clock = FixedClock(1_700_000_000_000)
stream = StringIO()
logger = logging.getLogger("rb_wf_ag.test.command_results")
logger = logging.getLogger("wfagent.test.command_results")
logger.handlers = []
logger.setLevel(logging.INFO)
logger.propagate = False
@ -1279,7 +1279,7 @@ def test_command_results_are_logged() -> None:
def test_command_timeouts_are_logged() -> None:
clock = FixedClock(1_700_000_000_000)
stream = StringIO()
logger = logging.getLogger("rb_wf_ag.test.command_timeouts")
logger = logging.getLogger("wfagent.test.command_timeouts")
logger.handlers = []
logger.setLevel(logging.INFO)
logger.propagate = False

View File

@ -18,24 +18,24 @@ delivery:
mode: webhook
# Template values for multiple agents/interfaces:
# - agent_id: stable logical agent name, for example:
# - rb-wf-ag
# - rb-wf-ag-lab
# - rb-wf-ag-prod
# - wfagent
# - wfagent-lab
# - wfagent-prod
# - agent_instance_id: unique runtime identity for one host/interface pair, for example:
# - rb-wf-ag@wlp3s0
# - rb-wf-ag@wlp2s0
# - rb-wf-ag-lab@wlan0
# - wfagent@wlp3s0
# - wfagent@wlp2s0
# - wfagent-lab@wlan0
#
# For a fleet with multiple agents, keep the same agent_id per deployment
# class and vary agent_instance_id per host or interface.
agent_id: rb-wf-ag
agent_instance_id: rb-wf-ag@wlp3s0
agent_id: wfagent
agent_instance_id: wfagent@wlp3s0
webhook:
enabled: true
url: http://127.0.0.1:8080/api/ingest
timeout_ms: 3000
headers:
X-Agent-Id: rb-wf-ag
X-Agent-Id: wfagent
retry:
max_attempts: 5
initial_backoff_ms: 250

View File

@ -1,28 +1,148 @@
# Wi-Fi Agents Backend
This is a separate backend project for receiving webhook deliveries from Wi-Fi agents.
This project is the delivery backend for `wfagent`.
It is intentionally isolated from the agent project:
It receives webhook deliveries from the agent, normalizes them, queues them for retry, and maps payload fields to downstream metric definitions.
- agent code lives in the repository root `src/rb_wf_ag`
- backend code lives in `backend/src/wi_fi_agents_backend`
- the two projects can be installed and deployed on different hosts
## Architecture
## Run
### Request flow
```bash
cd backend
python -m pip install -e .
wi-fi-agents-backend --config config.example.yaml
```text
HTTP ingest -> request normalization -> queue -> mapper -> sender
```
The backend is intentionally isolated from the agent project:
- agent code lives in [`../agent/src/wfagent`](../agent/src/wfagent)
- backend code lives in [`backend/src/wfagent_backend`](./src/wfagent_backend)
- the two projects can be installed and deployed independently
### Responsibilities
- accept webhook POST requests
- validate payload structure
- support canonical `items[]` payloads
- preserve queue state until delivery succeeds or TTL expires
- map selected fields to metric samples
- send metrics through `zabbix_sender`
## Components
Located in [`backend/src/wfagent_backend`](./src/wfagent_backend):
- [`cli.py`](./src/wfagent_backend/cli.py) - command line entry point
- [`config.py`](./src/wfagent_backend/config.py) - YAML configuration loader and validation
- [`server.py`](./src/wfagent_backend/server.py) - HTTP server and routing
- [`app.py`](./src/wfagent_backend/app.py) - ingest normalization and dispatch to the queue
- [`queue.py`](./src/wfagent_backend/queue.py) - in-memory batch queue with retry semantics
- [`mapping.py`](./src/wfagent_backend/mapping.py) - event-to-metric mapping
- [`sender.py`](./src/wfagent_backend/sender.py) - adapter for `zabbix_sender`
- [`contracts.py`](./src/wfagent_backend/contracts.py) - ingest and delivery data contracts
## Configuration
Use [`wfagent_backend.example.yaml`](./wfagent_backend.example.yaml) as the starting point.
### Main sections
- `server`
- `host`
- `port`
- `ingest_path`
- `health_path`
- `max_request_bytes`
- `agent`
- `agent_id`
- `agent_instance_id`
- `logging`
- `emit_ndjson`
- `log_level`
- `queue`
- `max_items`
- `batch_size`
- `item_ttl_ms`
- `retry`
- `zabbix`
- `sender_path`
- `server_host`
- `server_port`
- `timeout_ms`
- `extra_args`
- `mapping`
- metric rules and field extraction paths
## Ingest API
The backend exposes:
```text
POST /api/v1/ingest
GET /healthz
```
The canonical webhook contract is a batch envelope with `items[]`.
Legacy `message` and `messages` payloads are also accepted and normalized internally.
### Canonical request shape
The webhook contract is a batch envelope with `items[]`.
Each item includes:
- `item_id`
- `source_type`
- `source_id`
- `event_kind`
- `observed_at_unix_ms`
- `payload`
## Install
From the backend directory:
```bash
python -m pip install -e .
```
## Run
```bash
wfagent_backend --config wfagent_backend.example.yaml
```
Optional host and port overrides:
```bash
wfagent_backend --config wfagent_backend.example.yaml --host 127.0.0.1 --port 8080
```
## Deployment
### Local deployment
1. Create a virtual environment.
2. Install the backend in editable mode.
3. Start the server with a config file.
4. Point the agent delivery URL at `http://127.0.0.1:8080/api/v1/ingest`.
### Production deployment
1. Bind the backend to a private interface or localhost.
2. Place it behind a reverse proxy if you need TLS or authentication.
3. Keep `zabbix_sender` and network access available on the backend host.
4. Increase queue capacity if delivery latency is expected.
## Example
The included [`wfagent_backend.example.yaml`](./wfagent_backend.example.yaml) shows a minimal setup with:
- HTTP listener on port `8080`
- ingest path `/api/v1/ingest`
- health path `/healthz`
- one mapping rule for BSS signal metrics
## Testing
Run the backend tests from the repository root:
```bash
pytest backend/tests
```

View File

@ -3,7 +3,7 @@ requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "wi-fi-agents-backend"
name = "wfagent_backend"
version = "0.1.0"
description = "Webhook backend for Wi-Fi agents"
readme = "README.md"
@ -13,7 +13,7 @@ dependencies = [
]
[project.scripts]
wi-fi-agents-backend = "wi_fi_agents_backend.cli:main"
wfagent_backend = "wfagent_backend.cli:main"
[tool.setuptools]
package-dir = {"" = "src"}

View File

@ -160,35 +160,7 @@ class BackendApp:
"rejected_reasons": rejected_reasons,
}
if "messages" in data or "message" in data:
messages = data.get("messages")
if messages is None:
messages = [data.get("message")]
if not isinstance(messages, list):
raise ValueError("messages must be a list")
canonical_items = []
for index, message in enumerate(messages):
if not isinstance(message, Mapping):
rejected_item_ids.append(f"legacy-{index}")
rejected_reasons.append("message must be a mapping")
continue
canonical_items.append(self._coerce_legacy_message(message, agent_id))
from time import time
batch = DeliveryBatch(
batch_id=str(data.get("batch_id") or new_id("del")),
agent_id=str(data.get("agent_id") or agent_id),
agent_instance_id=str(
data.get("agent_instance_id") or agent_instance_id
),
sent_at_unix_ms=int(time() * 1000),
items=canonical_items,
)
return batch, {
"rejected_item_ids": rejected_item_ids,
"rejected_reasons": rejected_reasons,
}
raise ValueError("request must contain items, messages, or message")
raise ValueError("request must contain items")
def _coerce_item(self, raw_item: Any) -> DeliveryItem:
data = _as_mapping(raw_item)
@ -239,46 +211,6 @@ class BackendApp:
payload=dict(payload),
)
def _coerce_legacy_message(
self, message: Mapping[str, Any], agent_id: str
) -> DeliveryItem:
inner_payload = message.get("payload")
payload = (
dict(inner_payload) if isinstance(inner_payload, Mapping) else dict(message)
)
message_id = str(message.get("message_id") or new_id("msg"))
message_kind = str(message.get("message_kind") or "event")
timestamp = message.get("timestamp")
if not isinstance(timestamp, int):
from time import time
timestamp = int(time() * 1000)
target = DeliveryTarget(
kind="agent",
value=str(message.get("target") or agent_id),
)
return DeliveryItem(
item_id=message_id,
item_kind="event",
source_type=str(message.get("source_type") or "runtime"),
source_id=str(message.get("source_id") or agent_id),
event_kind=message_kind,
observed_at_unix_ms=timestamp,
correlation_id=(
message.get("correlation_id")
if isinstance(message.get("correlation_id"), str)
else None
),
causation_id=(
message.get("causation_id")
if isinstance(message.get("causation_id"), str)
else None
),
target=target,
data_kind=str(message.get("data_kind") or message_kind),
payload=payload,
)
def _normalize_item(
self, batch: DeliveryBatch, item: DeliveryItem, remote_addr: str | None
) -> NormalizedEvent:

View File

@ -12,7 +12,7 @@ from .server import create_server
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="wi-fi-agents-backend")
parser = argparse.ArgumentParser(prog="wfagent_backend")
parser.add_argument("--config", required=True, help="Path to YAML configuration")
parser.add_argument("--host", default=None, help="Override listen host")
parser.add_argument("--port", default=None, type=int, help="Override listen port")
@ -32,7 +32,7 @@ def main(argv: Sequence[str] | None = None) -> int:
server = create_server(host, port, app)
app.start()
try:
logging.getLogger("wi_fi_agents_backend").info(
logging.getLogger("wfagent_backend").info(
"backend listening on %s:%s", host, port
)
server.serve_forever()

View File

@ -129,7 +129,6 @@ class AgentConfig:
@dataclass(slots=True)
class BackendConfig:
http: HttpServerConfig
compatibility_accept_legacy_shapes: bool
agent: AgentConfig
logging: LoggingConfig
queue: QueueConfig
@ -174,7 +173,6 @@ def load_backend_config(source: str | Path | Mapping[str, Any]) -> BackendConfig
data = _load_yaml_document(source)
server = _ensure_mapping(data.get("server", {}), "server")
compatibility = _ensure_mapping(data.get("compatibility", {}), "compatibility")
agent = _ensure_mapping(data.get("agent", {}), "agent")
logging = _ensure_mapping(data.get("logging", {}), "logging")
queue = _ensure_mapping(data.get("queue", {}), "queue")
@ -202,13 +200,9 @@ def load_backend_config(source: str | Path | Mapping[str, Any]) -> BackendConfig
server.get("max_request_bytes", 262144), "server.max_request_bytes"
),
),
compatibility_accept_legacy_shapes=_ensure_bool(
compatibility.get("accept_legacy_shapes", True),
"compatibility.accept_legacy_shapes",
),
agent=AgentConfig(
agent_id=_ensure_str(
agent.get("agent_id", "wi-fi-agents-backend"), "agent.agent_id"
agent.get("agent_id", "wfagent_backend"), "agent.agent_id"
),
agent_instance_id=(
_ensure_str(agent["agent_instance_id"], "agent.agent_instance_id")

View File

@ -7,10 +7,12 @@ from pathlib import Path
from textwrap import dedent
from urllib import error, request
from wi_fi_agents_backend.app import BackendApp
from wi_fi_agents_backend.config import load_backend_config
from wi_fi_agents_backend.server import create_server
from wi_fi_agents_backend.sender import SenderResult, ZabbixSenderAdapter
import pytest
from wfagent_backend.app import BackendApp
from wfagent_backend.config import load_backend_config
from wfagent_backend.server import create_server
from wfagent_backend.sender import SenderResult, ZabbixSenderAdapter
class FakeSender(ZabbixSenderAdapter):
@ -32,11 +34,9 @@ def _config(tmp_path: Path) -> Path:
ingest_path: /api/v1/ingest
health_path: /healthz
max_request_bytes: 262144
compatibility:
accept_legacy_shapes: true
agent:
agent_id: rb-wf-ag
agent_instance_id: rb-wf-ag@test
agent_id: wfagent
agent_instance_id: wfagent@test
logging:
emit_ndjson: true
log_level: info
@ -87,8 +87,8 @@ def test_backend_accepts_canonical_batch_and_maps_multiple_metrics(
response = app.handle_request(
{
"batch_id": "del-1",
"agent_id": "rb-wf-ag",
"agent_instance_id": "rb-wf-ag@test",
"agent_id": "wfagent",
"agent_instance_id": "wfagent@test",
"sent_at_unix_ms": 1000,
"items": [
{
@ -129,66 +129,41 @@ def test_backend_accepts_canonical_batch_and_maps_multiple_metrics(
assert lines[0]["payload"]["changed"]["Signal"] == -41
def test_backend_accepts_legacy_single_message(tmp_path: Path) -> None:
def test_backend_rejects_unsupported_message_shapes(
tmp_path: Path,
) -> None:
config = load_backend_config(_config(tmp_path))
sender = FakeSender()
stdout = StringIO()
app = BackendApp(config=config, stdout=stdout, sender=sender)
response = app.handle_request(
{
"agent_id": "rb-wf-ag",
"message": {
"message_id": "m-1",
"message_kind": "wifi_event",
"timestamp": 1000,
"payload": {"state": "completed"},
},
}
)
assert response["accepted_count"] == 1
assert response["rejected_count"] == 0
assert "state" in json.loads(stdout.getvalue())["payload"]
assert sender.sent_batches == []
def test_backend_accepts_legacy_messages_list(tmp_path: Path) -> None:
config = load_backend_config(_config(tmp_path))
sender = FakeSender()
stdout = StringIO()
app = BackendApp(config=config, stdout=stdout, sender=sender)
response = app.handle_request(
{
"agent_id": "rb-wf-ag",
"messages": [
{
with pytest.raises(ValueError, match="request must contain items"):
app.handle_request(
{
"agent_id": "wfagent",
"message": {
"message_id": "m-1",
"message_kind": "wifi_event",
"timestamp": 1000,
"payload": {"state": "completed"},
},
{
"message_id": "m-2",
"message_kind": "wifi_event",
"timestamp": 1001,
"payload": {"state": "roaming"},
},
],
}
)
}
)
assert response["accepted_count"] == 2
assert response["rejected_count"] == 0
lines = [
json.loads(line) for line in stdout.getvalue().splitlines() if line.strip()
]
assert [line["payload"]["state"] for line in lines] == [
"completed",
"roaming",
]
assert sender.sent_batches == []
with pytest.raises(ValueError, match="request must contain items"):
app.handle_request(
{
"agent_id": "wfagent",
"messages": [
{
"message_id": "m-1",
"message_kind": "wifi_event",
"timestamp": 1000,
"payload": {"state": "completed"},
}
],
}
)
def test_backend_http_returns_400_and_404_for_invalid_requests(
@ -216,6 +191,28 @@ def test_backend_http_returns_400_and_404_for_invalid_requests(
except error.HTTPError as exc:
assert exc.code == 400
unsupported_message_request = request.Request(
f"{base_url}/api/v1/ingest",
data=json.dumps(
{
"agent_id": "wfagent",
"message": {
"message_id": "m-1",
"message_kind": "wifi_event",
"timestamp": 1000,
"payload": {"state": "completed"},
},
}
).encode("utf-8"),
method="POST",
headers={"Content-Type": "application/json"},
)
try:
request.urlopen(unsupported_message_request, timeout=2)
raise AssertionError("expected HTTP 400 for unsupported message payload")
except error.HTTPError as exc:
assert exc.code == 400
missing_path = request.Request(
f"{base_url}/api/v1/missing",
data=b"{}",

View File

@ -5,12 +5,9 @@ server:
health_path: /healthz
max_request_bytes: 262144
compatibility:
accept_legacy_shapes: true
agent:
agent_id: wi-fi-agents-backend
agent_instance_id: wi-fi-agents-backend@host01
agent_id: wfagent_backend
agent_instance_id: wfagent_backend@host01
logging:
emit_ndjson: true
@ -48,4 +45,3 @@ mapping:
- key: wifi.bss.age
host_path: target.value
value_path: payload.changed.Age

View File

@ -359,7 +359,7 @@ The backend should normalize them into this canonical shape before any downstrea
```yaml
batch_id: del-7f3f8c3d3f8b4f7e8e9e8af90c7c9b91
agent_id: agent-wlp3s0-01
agent_instance_id: rb-wf-ag@host01
agent_instance_id: wfagent@host01
sent_at_unix_ms: 1777782231298
items:
- item_id: evt-4b4c27f0436a4a28b8eee672d6594ede

View File

@ -1,5 +1,5 @@
{
"include": ["src", "tests", "backend/src", "backend/tests"],
"extraPaths": ["src", "backend/src"],
"include": ["agent/src", "agent/tests", "backend/src", "backend/tests"],
"extraPaths": ["agent/src", "backend/src"],
"typeCheckingMode": "standard"
}