init commit
This commit is contained in:
commit
2c8c4c1779
|
|
@ -0,0 +1,29 @@
|
|||
.*_cache/
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
__pycache__/
|
||||
*.so
|
||||
*.dylib
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
*.egg
|
||||
*.log
|
||||
*.bak
|
||||
*.swp
|
||||
*.swo
|
||||
*.tmp
|
||||
*.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
*.iml
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,924 @@
|
|||
# Wi‑Fi Event/Command Bridge for `wpa_supplicant`
|
||||
|
||||
## Purpose
|
||||
|
||||
This document defines:
|
||||
|
||||
- a formal architecture for an application module that uses:
|
||||
- D-Bus for the `wpa_supplicant` D-Bus tree
|
||||
- Unix socket for `wpa_supplicant` `ctrl_iface`
|
||||
- a ready YAML configuration schema
|
||||
- API skeleton for models, classes, and functions
|
||||
|
||||
The module must:
|
||||
|
||||
- receive events from configured sources
|
||||
- apply source-specific filters
|
||||
- classify events
|
||||
- serialize selected events to **stdout** as **NDJSON**
|
||||
- trigger commands for selected events
|
||||
- execute commands via the appropriate destination
|
||||
- distinguish:
|
||||
- execution result of the command inside the application
|
||||
- data returned by the external destination
|
||||
|
||||
The D-Bus methods, signals, and properties listed below are based on the `wpa_supplicant` D-Bus API documentation. citeturn754241view0
|
||||
The `ctrl_iface` commands and unsolicited events listed below are based on the documented `wpa_supplicant` control interface. citeturn298527view3turn298527view4turn298527view1turn298527view0
|
||||
|
||||
---
|
||||
|
||||
## Main source assumptions
|
||||
|
||||
### D-Bus source
|
||||
|
||||
The `wpa_supplicant` D-Bus API exposes:
|
||||
|
||||
- main object interface `fi.w1.wpa_supplicant1`
|
||||
- interface object interface `fi.w1.wpa_supplicant1.Interface`
|
||||
- main object methods:
|
||||
- `CreateInterface`
|
||||
- `RemoveInterface`
|
||||
- `GetInterface`
|
||||
- interface object methods including:
|
||||
- `Scan`
|
||||
- `Disconnect`
|
||||
- `AddNetwork`
|
||||
- `RemoveNetwork`
|
||||
- `RemoveAllNetworks`
|
||||
- `SelectNetwork`
|
||||
- `Reassociate`
|
||||
- `Reattach`
|
||||
- `Reconnect`
|
||||
- main object signals:
|
||||
- `InterfaceAdded`
|
||||
- `InterfaceRemoved`
|
||||
- `PropertiesChanged` citeturn754241view0
|
||||
|
||||
### `ctrl_iface` source and destination
|
||||
|
||||
The control interface provides commands including:
|
||||
|
||||
- `STATUS`
|
||||
- `STATUS-VERBOSE`
|
||||
- `REASSOCIATE`
|
||||
- `RECONNECT`
|
||||
- `ATTACH`
|
||||
- `DETACH`
|
||||
- `DISCONNECT`
|
||||
- `SCAN`
|
||||
- `SCAN_RESULTS`
|
||||
- `BSS`
|
||||
- `SELECT_NETWORK`
|
||||
- `ENABLE_NETWORK`
|
||||
- `DISABLE_NETWORK`
|
||||
- `RECONFIGURE`
|
||||
- `TERMINATE` citeturn298527view3turn298527view4turn298527view1turn298527view0
|
||||
|
||||
After `ATTACH`, unsolicited control interface events can be received, including examples such as:
|
||||
|
||||
- `CTRL-EVENT-SCAN-RESULTS`
|
||||
- `CTRL-EVENT-BSS-ADDED`
|
||||
- `CTRL-EVENT-BSS-REMOVED` citeturn298527view1turn298527view0
|
||||
|
||||
### Runtime-generated internal events
|
||||
|
||||
The application must also generate and recognize internal runtime events:
|
||||
|
||||
- `start`
|
||||
- `reload`
|
||||
- `stop`
|
||||
- `timer_tick`
|
||||
|
||||
`timer_tick` is emitted by a built-in service event source with a configurable interval.
|
||||
|
||||
### Output format
|
||||
|
||||
Serialized events are written to **stdout** in **NDJSON / JSON Lines** form: one UTF-8 JSON object per line. This is a standard line-oriented streaming format. citeturn754241view0turn298527view0
|
||||
|
||||
---
|
||||
|
||||
## Architectural principles
|
||||
|
||||
1. **Sources and destinations are separate concerns**
|
||||
- source adapters receive events
|
||||
- command clients execute commands
|
||||
|
||||
2. **Listeners must not execute commands directly**
|
||||
- listeners publish source events into the pipeline
|
||||
- trigger logic decides whether to create a command
|
||||
- dispatcher selects the destination
|
||||
|
||||
3. **Runtime events are first-class events**
|
||||
- they pass through the same filter / classifier / serializer / trigger flow
|
||||
|
||||
4. **Serialization target is stdout**
|
||||
- selected events are serialized to NDJSON only after classification
|
||||
|
||||
5. **Execution result and returned data are distinct**
|
||||
- the application must represent both explicitly
|
||||
|
||||
---
|
||||
|
||||
## Formal module architecture
|
||||
|
||||
### Top-level flow
|
||||
|
||||
```text
|
||||
DBus Source -----------\
|
||||
\
|
||||
Runtime Event Source ----> Source Filters -> Event Normalizer -> Event Classifier -> NDJSON Serializer -> stdout
|
||||
/ |
|
||||
CtrlIface Source ------/ |
|
||||
|
|
||||
-> Trigger Engine -> Command Dispatcher
|
||||
|
|
||||
+-> DBus Command Client
|
||||
+-> CtrlIface Command Client
|
||||
```
|
||||
|
||||
### Module list
|
||||
|
||||
#### Source adapters
|
||||
- `DbusEventSource`
|
||||
- `CtrlIfaceEventSource`
|
||||
- `RuntimeEventSource`
|
||||
|
||||
#### Event processing
|
||||
- `SourceFilterChain`
|
||||
- `EventNormalizer`
|
||||
- `EventClassifier`
|
||||
- `NdjsonSerializer`
|
||||
- `StdoutOutputWriter`
|
||||
|
||||
#### Trigger and command side
|
||||
- `TriggerEngine`
|
||||
- `TriggerLoopGuard`
|
||||
- `CommandDispatcher`
|
||||
- `DbusCommandClient`
|
||||
- `CtrlIfaceCommandClient`
|
||||
|
||||
#### Shared services
|
||||
- `Clock`
|
||||
- `CorrelationIdProvider`
|
||||
- `Observability`
|
||||
- `AppLifecycleService`
|
||||
- `ConfigManager`
|
||||
|
||||
---
|
||||
|
||||
## Unified event and command model
|
||||
|
||||
### Raw source event
|
||||
|
||||
```python
|
||||
class RawSourceEvent:
|
||||
event_id: str
|
||||
source_type: str # dbus | ctrl_iface | runtime
|
||||
source_id: str # dbus.wpa, ctrl_iface.wpa, runtime
|
||||
observed_at_unix_ms: int
|
||||
raw_payload: object
|
||||
```
|
||||
|
||||
### Normalized event
|
||||
|
||||
```python
|
||||
class NormalizedEvent:
|
||||
event_id: str
|
||||
source_type: str
|
||||
source_id: str
|
||||
event_kind: str
|
||||
observed_at_unix_ms: int
|
||||
severity: str
|
||||
payload_raw: object
|
||||
payload_structured: dict
|
||||
correlation_id: str | None
|
||||
causation_id: str | None
|
||||
```
|
||||
|
||||
### Event disposition
|
||||
|
||||
```python
|
||||
class EventDisposition:
|
||||
action: str # drop | serialize_only | serialize_and_trigger
|
||||
classifier_rule_id: str | None
|
||||
trigger_rule_ids: list[str]
|
||||
```
|
||||
|
||||
### Logical command request
|
||||
|
||||
```python
|
||||
class CommandRequest:
|
||||
command_id: str
|
||||
command_kind: str
|
||||
destination_hint: str | None # dbus | ctrl_iface | auto
|
||||
arguments: dict
|
||||
triggered_by_event_id: str | None
|
||||
correlation_id: str | None
|
||||
priority: str | None
|
||||
not_before_unix_ms: int | None
|
||||
expires_at_unix_ms: int | None
|
||||
```
|
||||
|
||||
### Command execution result vs returned data
|
||||
|
||||
```python
|
||||
class CommandExecutionResult:
|
||||
execution_status: str # accepted | sent | succeeded | failed | timed_out | unsupported
|
||||
execution_error_code: str | None
|
||||
execution_error_message: str | None
|
||||
|
||||
class CommandReturnedData:
|
||||
data_type: str # none | text | kv | structured | event_like
|
||||
payload: object | None
|
||||
|
||||
class CommandResult:
|
||||
command_id: str
|
||||
destination: str
|
||||
execution: CommandExecutionResult
|
||||
returned_data: CommandReturnedData
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Source behavior model
|
||||
|
||||
### D-Bus source
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- connect to the system bus
|
||||
- resolve the root object `fi.w1.wpa_supplicant1`
|
||||
- resolve interface object paths through `GetInterface`
|
||||
- subscribe to relevant signals and/or properties
|
||||
- convert source payload into `RawSourceEvent`
|
||||
|
||||
#### D-Bus method list to reflect in the API skeleton
|
||||
|
||||
##### Main object `fi.w1.wpa_supplicant1`
|
||||
- `CreateInterface(args) -> interface`
|
||||
- `RemoveInterface(interface)`
|
||||
- `GetInterface(ifname) -> interface` citeturn754241view0
|
||||
|
||||
##### Interface object `fi.w1.wpa_supplicant1.Interface`
|
||||
- `Scan(args)`
|
||||
- `Disconnect()`
|
||||
- `AddNetwork(args) -> network`
|
||||
- `RemoveNetwork(network)`
|
||||
- `RemoveAllNetworks()`
|
||||
- `SelectNetwork(network)`
|
||||
- `SignalPoll()`
|
||||
- `SubscribeProbeReq()`
|
||||
- `UnsubscribeProbeReq()`
|
||||
- `Reassociate()`
|
||||
- `Reattach()`
|
||||
- `FlushBSS(args)`
|
||||
- `Reconnect()` citeturn754241view0
|
||||
|
||||
##### Main signal examples
|
||||
- `InterfaceAdded(interface, properties)`
|
||||
- `InterfaceRemoved(interface)`
|
||||
- `PropertiesChanged(properties)` citeturn754241view0
|
||||
|
||||
### `ctrl_iface` source
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- connect to the Unix socket
|
||||
- optionally issue `ATTACH`
|
||||
- receive unsolicited event lines
|
||||
- convert each unsolicited line into `RawSourceEvent`
|
||||
|
||||
#### Control interface commands to reflect in the API skeleton
|
||||
- `STATUS`
|
||||
- `STATUS-VERBOSE`
|
||||
- `REASSOCIATE`
|
||||
- `RECONNECT`
|
||||
- `ATTACH`
|
||||
- `DETACH`
|
||||
- `DISCONNECT`
|
||||
- `SCAN`
|
||||
- `SCAN_RESULTS`
|
||||
- `BSS`
|
||||
- `RECONFIGURE`
|
||||
- `TERMINATE` citeturn298527view3turn298527view4turn298527view1turn298527view0
|
||||
|
||||
#### Unsolicited event examples
|
||||
- `CTRL-EVENT-SCAN-RESULTS`
|
||||
- `CTRL-EVENT-BSS-ADDED`
|
||||
- `CTRL-EVENT-BSS-REMOVED` citeturn298527view1turn298527view0
|
||||
|
||||
### Runtime event source
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- emit `start`
|
||||
- emit `reload`
|
||||
- emit `stop`
|
||||
- emit `every100ms`
|
||||
|
||||
The `timer_tick` event is driven by the application timer source and uses a configurable interval in milliseconds.
|
||||
|
||||
---
|
||||
|
||||
## Event processing rules
|
||||
|
||||
|
||||
## Rule matching semantics
|
||||
|
||||
### AND/OR logic inside one rule
|
||||
|
||||
Inside a single rule:
|
||||
|
||||
- different fields are matched with **AND** logic;
|
||||
- multiple values inside one field are matched with **OR** logic.
|
||||
|
||||
This means that one rule matches only if all specified fields match, while each individual field may match any one value from its configured value list.
|
||||
|
||||
### D-Bus filter fields
|
||||
|
||||
A D-Bus filter rule may contain the following optional fields:
|
||||
|
||||
- `Interface`
|
||||
- `Path`
|
||||
- `Member`
|
||||
|
||||
Each field accepts a list of possible values.
|
||||
|
||||
A D-Bus event matches the rule if:
|
||||
|
||||
- `Interface` matches any configured value, if `Interface` is present;
|
||||
- `Path` matches any configured value, if `Path` is present;
|
||||
- `Member` matches any configured value, if `Member` is present;
|
||||
|
||||
and all specified fields match together.
|
||||
|
||||
Formally:
|
||||
|
||||
```text
|
||||
(Interface in InterfaceList, if specified)
|
||||
AND
|
||||
(Path in PathList, if specified)
|
||||
AND
|
||||
(Member in MemberList, if specified)
|
||||
```
|
||||
|
||||
### `ctrl_iface` filter fields
|
||||
|
||||
A `ctrl_iface` filter rule is matched by the event kind, for example:
|
||||
|
||||
- `CTRL-EVENT-SCAN-RESULTS`
|
||||
- `CTRL-EVENT-BSS-ADDED`
|
||||
- `CTRL-EVENT-BSS-REMOVED`
|
||||
|
||||
If `event_kind_in` is configured, the rule matches when the received `ctrl_iface` event kind equals any value from the configured list.
|
||||
|
||||
### Runtime filter fields
|
||||
|
||||
A runtime filter rule is matched by the runtime event kind, for example:
|
||||
|
||||
- `start`
|
||||
- `reload`
|
||||
- `stop`
|
||||
- `timer_tick`
|
||||
|
||||
|
||||
### Per-source filters
|
||||
|
||||
Per-source filters are applied before normalization.
|
||||
|
||||
Examples:
|
||||
- suppress low-value D-Bus property changes
|
||||
- keep only selected `ctrl_iface` unsolicited events
|
||||
- enable or disable `timer_tick`
|
||||
|
||||
### Event classifier
|
||||
|
||||
Classifier decisions:
|
||||
- `drop`
|
||||
- `serialize_only`
|
||||
- `serialize_and_trigger`
|
||||
|
||||
### Trigger rules
|
||||
|
||||
A trigger rule must define:
|
||||
- event match conditions
|
||||
- logical command kind
|
||||
- destination
|
||||
- arguments
|
||||
- cooldown / debounce policy
|
||||
|
||||
### Loop guard
|
||||
|
||||
The application must prevent loops such as:
|
||||
|
||||
- event -> command -> event -> command
|
||||
- repeated `timer_tick` triggers
|
||||
- repeated disconnect/reassociate oscillation
|
||||
|
||||
---
|
||||
|
||||
## NDJSON serialization contract
|
||||
|
||||
Each serialized event is written to stdout as one JSON object per line.
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{"event_id":"e-1001","source_type":"dbus","source_id":"dbus.wpa","event_kind":"state_changed","observed_at_unix_ms":1760000000000,"severity":"info","payload":{"state":"completed"}}
|
||||
```
|
||||
|
||||
Runtime event example:
|
||||
|
||||
```json
|
||||
{"event_id":"e-1002","source_type":"runtime","source_id":"runtime","event_kind":"start","observed_at_unix_ms":1760000000100,"severity":"info","payload":{}}
|
||||
```
|
||||
|
||||
No JSON arrays are used for streaming output.
|
||||
|
||||
---
|
||||
|
||||
## Ready YAML configuration schema
|
||||
|
||||
```yaml
|
||||
version: 1
|
||||
|
||||
runtime:
|
||||
generate_events:
|
||||
start: true
|
||||
reload: true
|
||||
stop: true
|
||||
timer_tick: true
|
||||
timers:
|
||||
timer_tick_interval_ms: 100
|
||||
|
||||
sources:
|
||||
dbus:
|
||||
enabled: true
|
||||
bus: system
|
||||
service: fi.w1.wpa_supplicant1
|
||||
root_path: /fi/w1/wpa_supplicant1
|
||||
interface_name: fi.w1.wpa_supplicant1.Interface
|
||||
filters:
|
||||
- id: dbus-drop-debug-properties
|
||||
enabled: true
|
||||
match:
|
||||
event_kind: properties_changed
|
||||
payload_has_any_key:
|
||||
- DebugLevel
|
||||
- DebugTimestamp
|
||||
- DebugShowKeys
|
||||
action: drop
|
||||
|
||||
- id: dbus-keep-core-events
|
||||
enabled: true
|
||||
match:
|
||||
event_kind_in:
|
||||
- interface_added
|
||||
- interface_removed
|
||||
- properties_changed
|
||||
action: keep
|
||||
|
||||
ctrl_iface:
|
||||
enabled: true
|
||||
socket_path: /var/run/wpa_supplicant/wlan0
|
||||
attach_for_events: true
|
||||
filters:
|
||||
- id: ctrl-keep-core-events
|
||||
enabled: true
|
||||
match:
|
||||
event_kind_in:
|
||||
- CTRL-EVENT-SCAN-RESULTS
|
||||
- CTRL-EVENT-BSS-ADDED
|
||||
- CTRL-EVENT-BSS-REMOVED
|
||||
action: keep
|
||||
|
||||
- id: ctrl-drop-unmatched
|
||||
enabled: true
|
||||
match:
|
||||
any: true
|
||||
action: drop
|
||||
|
||||
runtime:
|
||||
enabled: true
|
||||
filters:
|
||||
- id: runtime-keep-core
|
||||
enabled: true
|
||||
match:
|
||||
event_kind_in:
|
||||
- start
|
||||
- reload
|
||||
- stop
|
||||
- timer_tick
|
||||
action: keep
|
||||
|
||||
classifier:
|
||||
rules:
|
||||
- id: serialize-runtime-start
|
||||
enabled: true
|
||||
match:
|
||||
source_type: runtime
|
||||
event_kind: start
|
||||
disposition: serialize_only
|
||||
|
||||
- id: serialize-runtime-reload
|
||||
enabled: true
|
||||
match:
|
||||
source_type: runtime
|
||||
event_kind: reload
|
||||
disposition: serialize_only
|
||||
|
||||
- id: serialize-runtime-stop
|
||||
enabled: true
|
||||
match:
|
||||
source_type: runtime
|
||||
event_kind: stop
|
||||
disposition: serialize_only
|
||||
|
||||
- id: serialize-runtime-timer-tick
|
||||
enabled: true
|
||||
match:
|
||||
source_type: runtime
|
||||
event_kind: timer_tick
|
||||
disposition: serialize_only
|
||||
|
||||
- id: serialize-dbus-properties
|
||||
enabled: true
|
||||
match:
|
||||
source_type: dbus
|
||||
event_kind: properties_changed
|
||||
disposition: serialize_only
|
||||
|
||||
- id: serialize-and-trigger-scan-results
|
||||
enabled: true
|
||||
match:
|
||||
source_type: ctrl_iface
|
||||
event_kind: CTRL-EVENT-SCAN-RESULTS
|
||||
disposition: serialize_and_trigger
|
||||
|
||||
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
|
||||
|
||||
- id: on-scan-results-fetch-bss
|
||||
enabled: true
|
||||
match:
|
||||
source_type: ctrl_iface
|
||||
event_kind: CTRL-EVENT-SCAN-RESULTS
|
||||
command:
|
||||
command_kind: bss_dump
|
||||
destination: ctrl_iface
|
||||
arguments:
|
||||
mode: iterative
|
||||
cooldown_ms: 5000
|
||||
max_retries: 0
|
||||
|
||||
- id: periodic-scan
|
||||
enabled: false
|
||||
match:
|
||||
source_type: runtime
|
||||
event_kind: timer_tick
|
||||
command:
|
||||
command_kind: scan
|
||||
destination: ctrl_iface
|
||||
arguments: {}
|
||||
cooldown_ms: 30000
|
||||
max_retries: 0
|
||||
|
||||
commands:
|
||||
dispatch:
|
||||
strategy: explicit_destination_only
|
||||
|
||||
dbus:
|
||||
enabled: true
|
||||
methods:
|
||||
create_interface:
|
||||
object: fi.w1.wpa_supplicant1
|
||||
method: CreateInterface
|
||||
remove_interface:
|
||||
object: fi.w1.wpa_supplicant1
|
||||
method: RemoveInterface
|
||||
get_interface:
|
||||
object: fi.w1.wpa_supplicant1
|
||||
method: GetInterface
|
||||
scan:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: Scan
|
||||
disconnect:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: Disconnect
|
||||
add_network:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: AddNetwork
|
||||
remove_network:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: RemoveNetwork
|
||||
remove_all_networks:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: RemoveAllNetworks
|
||||
select_network:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: SelectNetwork
|
||||
reassociate:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: Reassociate
|
||||
reattach:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: Reattach
|
||||
reconnect:
|
||||
object: fi.w1.wpa_supplicant1.Interface
|
||||
method: Reconnect
|
||||
|
||||
ctrl_iface:
|
||||
enabled: true
|
||||
commands:
|
||||
get_status: STATUS
|
||||
get_status_verbose: STATUS-VERBOSE
|
||||
disconnect: DISCONNECT
|
||||
scan: SCAN
|
||||
scan_results: SCAN_RESULTS
|
||||
bss_dump: BSS
|
||||
reassociate: REASSOCIATE
|
||||
reconnect: RECONNECT
|
||||
attach: ATTACH
|
||||
detach: DETACH
|
||||
reconfigure: RECONFIGURE
|
||||
terminate: TERMINATE
|
||||
|
||||
output:
|
||||
format: ndjson
|
||||
target: stdout
|
||||
flush_every_event: true
|
||||
|
||||
observability:
|
||||
emit_internal_metrics: true
|
||||
log_level: info
|
||||
|
||||
guards:
|
||||
trigger_loop_guard:
|
||||
enabled: true
|
||||
default_cooldown_ms: 5000
|
||||
dedup_window_ms: 3000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API skeleton
|
||||
|
||||
### Configuration models
|
||||
|
||||
```python
|
||||
class RuntimeConfig:
|
||||
generate_start: bool
|
||||
generate_reload: bool
|
||||
generate_stop: bool
|
||||
generate_timer_tick: bool
|
||||
timer_tick_interval_ms: int
|
||||
|
||||
class SourceFilterRule:
|
||||
rule_id: str
|
||||
enabled: bool
|
||||
match: dict
|
||||
action: str # keep | drop
|
||||
|
||||
class DbusSourceConfig:
|
||||
enabled: bool
|
||||
bus: str
|
||||
service: str
|
||||
root_path: str
|
||||
interface_name: str
|
||||
filters: list[SourceFilterRule]
|
||||
|
||||
class CtrlIfaceSourceConfig:
|
||||
enabled: bool
|
||||
socket_path: str
|
||||
attach_for_events: bool
|
||||
filters: list[SourceFilterRule]
|
||||
|
||||
class RuntimeSourceConfig:
|
||||
enabled: bool
|
||||
filters: list[SourceFilterRule]
|
||||
|
||||
class EventClassifierRule:
|
||||
rule_id: str
|
||||
enabled: bool
|
||||
match: dict
|
||||
disposition: str # drop | serialize_only | serialize_and_trigger
|
||||
|
||||
class TriggerRule:
|
||||
rule_id: str
|
||||
enabled: bool
|
||||
match: dict
|
||||
command: dict
|
||||
cooldown_ms: int
|
||||
max_retries: int
|
||||
|
||||
class OutputConfig:
|
||||
format: str # ndjson
|
||||
target: str # stdout
|
||||
flush_every_event: bool
|
||||
|
||||
class AppConfig:
|
||||
version: int
|
||||
runtime: RuntimeConfig
|
||||
dbus: DbusSourceConfig
|
||||
ctrl_iface: CtrlIfaceSourceConfig
|
||||
runtime_source: RuntimeSourceConfig
|
||||
classifier_rules: list[EventClassifierRule]
|
||||
trigger_rules: list[TriggerRule]
|
||||
output: OutputConfig
|
||||
```
|
||||
|
||||
### Source adapter interfaces
|
||||
|
||||
```python
|
||||
class EventSource:
|
||||
async def start(self) -> None: ...
|
||||
async def stop(self) -> None: ...
|
||||
async def read_event(self) -> RawSourceEvent | None: ...
|
||||
|
||||
class DbusEventSource(EventSource):
|
||||
async def connect(self) -> None: ...
|
||||
async def resolve_root_proxy(self) -> None: ...
|
||||
async def resolve_interface_proxy(self, ifname: str) -> None: ...
|
||||
async def subscribe_signals(self) -> None: ...
|
||||
async def read_event(self) -> RawSourceEvent | None: ...
|
||||
|
||||
class CtrlIfaceEventSource(EventSource):
|
||||
async def connect(self) -> None: ...
|
||||
async def attach(self) -> None: ...
|
||||
async def detach(self) -> None: ...
|
||||
async def read_event(self) -> RawSourceEvent | None: ...
|
||||
|
||||
class RuntimeEventSource(EventSource):
|
||||
async def emit_start(self) -> RawSourceEvent: ...
|
||||
async def emit_reload(self) -> RawSourceEvent: ...
|
||||
async def emit_stop(self) -> RawSourceEvent: ...
|
||||
async def emit_timer_tick(self) -> RawSourceEvent: ...
|
||||
```
|
||||
|
||||
### Source filter chain
|
||||
|
||||
```python
|
||||
class SourceFilterChain:
|
||||
def apply(self, event: RawSourceEvent, source_type: str) -> bool:
|
||||
...
|
||||
```
|
||||
|
||||
### Event normalization
|
||||
|
||||
```python
|
||||
class EventNormalizer:
|
||||
def normalize(self, event: RawSourceEvent) -> NormalizedEvent: ...
|
||||
```
|
||||
|
||||
### Event classifier
|
||||
|
||||
```python
|
||||
class EventClassifier:
|
||||
def classify(self, event: NormalizedEvent) -> EventDisposition: ...
|
||||
```
|
||||
|
||||
### NDJSON serializer and stdout writer
|
||||
|
||||
```python
|
||||
class NdjsonSerializer:
|
||||
def serialize(self, event: NormalizedEvent) -> str: ...
|
||||
|
||||
class StdoutOutputWriter:
|
||||
def write_line(self, line: str) -> None: ...
|
||||
```
|
||||
|
||||
### Trigger engine and loop guard
|
||||
|
||||
```python
|
||||
class TriggerLoopGuard:
|
||||
def allow(self, event: NormalizedEvent, trigger_rule_id: str) -> bool: ...
|
||||
|
||||
class TriggerEngine:
|
||||
def evaluate(self, event: NormalizedEvent, disposition: EventDisposition) -> list[CommandRequest]:
|
||||
...
|
||||
```
|
||||
|
||||
### Command dispatcher
|
||||
|
||||
```python
|
||||
class CommandDispatcher:
|
||||
async def dispatch(self, request: CommandRequest) -> CommandResult: ...
|
||||
def select_destination(self, request: CommandRequest) -> str: ...
|
||||
```
|
||||
|
||||
### D-Bus command client skeleton
|
||||
|
||||
```python
|
||||
class DbusCommandClient:
|
||||
async def create_interface(self, args: dict) -> CommandResult: ...
|
||||
async def remove_interface(self, interface_path: str) -> CommandResult: ...
|
||||
async def get_interface(self, ifname: str) -> CommandResult: ...
|
||||
|
||||
async def scan(self, args: dict) -> CommandResult: ...
|
||||
async def disconnect(self) -> CommandResult: ...
|
||||
async def add_network(self, args: dict) -> CommandResult: ...
|
||||
async def remove_network(self, network_path: str) -> CommandResult: ...
|
||||
async def remove_all_networks(self) -> CommandResult: ...
|
||||
async def select_network(self, network_path: str) -> CommandResult: ...
|
||||
async def reassociate(self) -> CommandResult: ...
|
||||
async def reattach(self) -> CommandResult: ...
|
||||
async def reconnect(self) -> CommandResult: ...
|
||||
```
|
||||
|
||||
These methods reflect the documented D-Bus API surface used by this module. citeturn754241view0
|
||||
|
||||
### `ctrl_iface` command client skeleton
|
||||
|
||||
```python
|
||||
class CtrlIfaceCommandClient:
|
||||
async def status(self) -> CommandResult: ...
|
||||
async def status_verbose(self) -> CommandResult: ...
|
||||
async def reassociate(self) -> CommandResult: ...
|
||||
async def reconnect(self) -> CommandResult: ...
|
||||
async def disconnect(self) -> CommandResult: ...
|
||||
async def scan(self) -> CommandResult: ...
|
||||
async def scan_results(self) -> CommandResult: ...
|
||||
async def bss(self, selector: str | None = None) -> CommandResult: ...
|
||||
async def attach(self) -> CommandResult: ...
|
||||
async def detach(self) -> CommandResult: ...
|
||||
async def reconfigure(self) -> CommandResult: ...
|
||||
async def terminate(self) -> CommandResult: ...
|
||||
```
|
||||
|
||||
These methods reflect the documented control interface command set used by this module. citeturn298527view3turn298527view4turn298527view1turn298527view0
|
||||
|
||||
### Lifecycle and orchestration skeleton
|
||||
|
||||
```python
|
||||
class AppLifecycleService:
|
||||
async def start(self) -> None: ...
|
||||
async def reload(self) -> None: ...
|
||||
async def stop(self) -> None: ...
|
||||
|
||||
class EventPipeline:
|
||||
async def ingest(self, event: RawSourceEvent) -> None: ...
|
||||
async def process(self, event: RawSourceEvent) -> None: ...
|
||||
|
||||
class ApplicationRuntime:
|
||||
async def run(self) -> None: ...
|
||||
async def handle_event(self, event: RawSourceEvent) -> None: ...
|
||||
async def handle_command_result(self, result: CommandResult) -> None: ...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Recommended command mapping policy
|
||||
|
||||
Commands should be issued to an explicitly configured destination without fallback.
|
||||
|
||||
Recommended practical split:
|
||||
|
||||
- **D-Bus**
|
||||
- interface discovery
|
||||
- structured object/path resolution
|
||||
- selected state/property calls
|
||||
- selected interface methods
|
||||
- **`ctrl_iface`**
|
||||
- status text retrieval
|
||||
- scan triggering
|
||||
- scan result text retrieval
|
||||
- detailed BSS dumping
|
||||
- reassociation/reconnect/disconnect commands
|
||||
- attach/detach for unsolicited text events
|
||||
|
||||
This split follows the documented command families and their strengths. Destination selection is defined by trigger rules or explicit command requests; the dispatcher does not apply fallback routing. citeturn754241view0turn298527view3turn298527view4turn298527view1turn298527view0
|
||||
|
||||
---
|
||||
|
||||
## Implementation rule
|
||||
|
||||
The module should follow this rule:
|
||||
|
||||
- source adapters are transport-specific and lightweight
|
||||
- all events, including runtime events, pass through one unified event pipeline
|
||||
- source-specific filters are applied before normalization
|
||||
- classifier and trigger rules are configuration-driven
|
||||
- NDJSON serialization is performed only after classification
|
||||
- commands are executed through a dedicated dispatcher
|
||||
- each command request targets an explicit destination without fallback
|
||||
- application-side execution status is always separated from destination-returned data
|
||||
- stdout is the only event serialization target in this module
|
||||
- Python, dbus-next, virtual-environment
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
- D-Bus API reference: `https://w1.fi/wpa_supplicant/devel/dbus.html`
|
||||
- ctrl_iface reference: `https://w1.fi/wpa_supplicant/devel/ctrl_iface_page.html`
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
# rb-wf-ag
|
||||
|
||||
Wi-Fi event/command bridge for `wpa_supplicant`.
|
||||
|
||||
The application:
|
||||
|
||||
- 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
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
python -m pip install -e .
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
rb-wf-ag --config config.yaml
|
||||
```
|
||||
|
||||
or:
|
||||
|
||||
```bash
|
||||
python -m rb_wf_ag --config config.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:
|
||||
|
||||
```bash
|
||||
pytest -m integration
|
||||
```
|
||||
|
||||
The smoke test connects to the socket, issues `STATUS`, and checks that a state response is returned.
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
pytest -m integration
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
The default suite is self-contained and does not require a live `wpa_supplicant`.
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
version: 1
|
||||
|
||||
runtime:
|
||||
generate_events:
|
||||
start: false
|
||||
reload: false
|
||||
stop: false
|
||||
timer_tick: true
|
||||
timers:
|
||||
timer_tick_interval_ms: 1000
|
||||
|
||||
sources:
|
||||
dbus:
|
||||
enabled: true
|
||||
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/wlp3s0
|
||||
attach_for_events: true
|
||||
filters: []
|
||||
|
||||
runtime:
|
||||
enabled: true
|
||||
filters: []
|
||||
|
||||
classifier:
|
||||
rules:
|
||||
- id: serialize-timer-tick-and-trigger
|
||||
enabled: true
|
||||
match:
|
||||
source_type: runtime
|
||||
event_kind: timer_tick
|
||||
disposition: serialize_and_trigger
|
||||
|
||||
- id: serialize-all-events
|
||||
enabled: true
|
||||
match:
|
||||
any: true
|
||||
disposition: serialize_only
|
||||
|
||||
triggers:
|
||||
rules:
|
||||
- id: every-second-status
|
||||
enabled: true
|
||||
match:
|
||||
source_type: runtime
|
||||
event_kind: timer_tick
|
||||
command:
|
||||
command_kind: get_status
|
||||
destination: ctrl_iface
|
||||
arguments: {}
|
||||
cooldown_ms: 1000
|
||||
max_retries: 0
|
||||
|
||||
commands:
|
||||
dispatch:
|
||||
strategy: explicit_destination_only
|
||||
|
||||
dbus:
|
||||
enabled: true
|
||||
methods: {}
|
||||
|
||||
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:
|
||||
enabled: true
|
||||
default_cooldown_ms: 5000
|
||||
dedup_window_ms: 3000
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
[build-system]
|
||||
requires = ["setuptools>=68", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "rb-wf-ag"
|
||||
version = "0.1.0"
|
||||
description = "Wi-Fi event/command bridge for wpa_supplicant"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"PyYAML>=6.0",
|
||||
"dbus-next>=0.2.3",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
rb-wf-ag = "rb_wf_ag.cli:main"
|
||||
|
||||
[tool.setuptools]
|
||||
package-dir = {"" = "src"}
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = "-q"
|
||||
markers = [
|
||||
"integration: tests that require a live wpa_supplicant or other external process",
|
||||
]
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"stubPath": "typings",
|
||||
"reportMissingImports": true,
|
||||
"reportMissingTypeStubs": false
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
"""Wi-Fi event/command bridge for wpa_supplicant."""
|
||||
|
||||
from .cli import build_application, main
|
||||
from .config import AppConfig, load_app_config
|
||||
from .models import (
|
||||
CommandExecutionResult,
|
||||
CommandRequest,
|
||||
CommandResult,
|
||||
CommandReturnedData,
|
||||
EventDisposition,
|
||||
NormalizedEvent,
|
||||
RawSourceEvent,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AppConfig",
|
||||
"CommandExecutionResult",
|
||||
"CommandRequest",
|
||||
"CommandResult",
|
||||
"CommandReturnedData",
|
||||
"EventDisposition",
|
||||
"NormalizedEvent",
|
||||
"RawSourceEvent",
|
||||
"build_application",
|
||||
"load_app_config",
|
||||
"main",
|
||||
]
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
from .cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Sequence
|
||||
|
||||
from .commands import CommandDispatcher
|
||||
from .config import AppConfig, load_app_config
|
||||
from .lifecycle import AppLifecycleService
|
||||
from .pipeline import (
|
||||
ApplicationRuntime,
|
||||
EventClassifier,
|
||||
EventNormalizer,
|
||||
EventPipeline,
|
||||
NdjsonSerializer,
|
||||
SourceFilterChain,
|
||||
StdoutOutputWriter,
|
||||
TriggerEngine,
|
||||
TriggerLoopGuard,
|
||||
)
|
||||
from .services import Clock, CorrelationIdProvider, Observability
|
||||
from .sources import CtrlIfaceEventSource, DbusEventSource, RuntimeEventSource
|
||||
from .protocols import EventSourceProtocol
|
||||
|
||||
|
||||
def build_application(config: AppConfig) -> ApplicationRuntime:
|
||||
observability = Observability(
|
||||
emit_internal_metrics=config.observability.emit_internal_metrics,
|
||||
log_level=config.observability.log_level,
|
||||
)
|
||||
clock = Clock()
|
||||
correlation_ids = CorrelationIdProvider()
|
||||
|
||||
runtime_source = RuntimeEventSource(
|
||||
config.runtime, clock=clock, correlation_ids=correlation_ids
|
||||
)
|
||||
filter_chain = SourceFilterChain(
|
||||
{
|
||||
"dbus": config.dbus.filters,
|
||||
"ctrl_iface": config.ctrl_iface.filters,
|
||||
"runtime": config.runtime_source.filters,
|
||||
},
|
||||
observability=observability,
|
||||
)
|
||||
pipeline = EventPipeline(
|
||||
filter_chain=filter_chain,
|
||||
normalizer=EventNormalizer(clock=clock, correlation_ids=correlation_ids),
|
||||
classifier=EventClassifier(config.classifier_rules),
|
||||
serializer=NdjsonSerializer(),
|
||||
output_writer=StdoutOutputWriter(),
|
||||
trigger_engine=TriggerEngine(
|
||||
rules=config.trigger_rules,
|
||||
loop_guard=TriggerLoopGuard(
|
||||
default_cooldown_ms=int(
|
||||
config.guards.trigger_loop_guard.get("default_cooldown_ms", 5000)
|
||||
),
|
||||
dedup_window_ms=int(
|
||||
config.guards.trigger_loop_guard.get("dedup_window_ms", 3000)
|
||||
),
|
||||
),
|
||||
clock=clock,
|
||||
),
|
||||
command_dispatcher=CommandDispatcher(config),
|
||||
observability=observability,
|
||||
)
|
||||
sources: list[EventSourceProtocol] = [runtime_source]
|
||||
if config.dbus.enabled:
|
||||
sources.append(
|
||||
DbusEventSource(config.dbus, clock=clock, correlation_ids=correlation_ids)
|
||||
)
|
||||
if config.ctrl_iface.enabled:
|
||||
sources.append(
|
||||
CtrlIfaceEventSource(
|
||||
config.ctrl_iface, clock=clock, correlation_ids=correlation_ids
|
||||
)
|
||||
)
|
||||
lifecycle = AppLifecycleService(runtime_source, observability=observability)
|
||||
return ApplicationRuntime(
|
||||
sources=sources,
|
||||
pipeline=pipeline,
|
||||
lifecycle_service=lifecycle,
|
||||
observability=observability,
|
||||
)
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="rb-wf-ag")
|
||||
parser.add_argument("--config", required=True, help="Path to YAML configuration")
|
||||
parser.add_argument("--log-level", default=None, help="Override log level")
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = _build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
config = load_app_config(Path(args.config))
|
||||
log_level = args.log_level or config.observability.log_level
|
||||
logging.basicConfig(level=getattr(logging, log_level.upper(), logging.INFO))
|
||||
runtime = build_application(config)
|
||||
try:
|
||||
asyncio.run(runtime.run())
|
||||
except OSError as exc:
|
||||
print(f"rb-wf-ag: startup failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
|
@ -0,0 +1,545 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from tempfile import gettempdir
|
||||
from typing import Any, Mapping
|
||||
|
||||
from dbus_next.aio.message_bus import MessageBus
|
||||
from dbus_next.constants import BusType
|
||||
|
||||
from .config import AppConfig, CommandEndpoint
|
||||
from .models import (
|
||||
CommandExecutionResult,
|
||||
CommandRequest,
|
||||
CommandResult,
|
||||
CommandReturnedData,
|
||||
json_safe,
|
||||
)
|
||||
from .protocols import CtrlIfaceCommandClientProtocol, DbusCommandClientProtocol
|
||||
|
||||
|
||||
def _kv_payload(text: str) -> dict[str, str]:
|
||||
result: dict[str, str] = {}
|
||||
for line in text.splitlines():
|
||||
if "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
result[key.strip()] = value.strip()
|
||||
return result
|
||||
|
||||
|
||||
def _destination_name(value: str | None) -> str:
|
||||
if value is None:
|
||||
return "auto"
|
||||
return value.strip().lower()
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CtrlIfaceCommandClient:
|
||||
socket_path: str
|
||||
_socket: socket.socket | None = None
|
||||
_local_path: str | None = None
|
||||
_connected: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
return None
|
||||
|
||||
async def connect(self) -> None:
|
||||
if self._connected:
|
||||
return
|
||||
socket_path = Path(self.socket_path)
|
||||
if not socket_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"ctrl_iface socket path does not exist: {socket_path}"
|
||||
)
|
||||
if not socket_path.is_socket():
|
||||
raise FileNotFoundError(
|
||||
f"ctrl_iface socket path is not a Unix socket: {socket_path}"
|
||||
)
|
||||
ctrl_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
local_path = f"{gettempdir()}/wpa_ctrl_{os.getpid()}-{id(self)}"
|
||||
try:
|
||||
Path(local_path).unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
ctrl_socket.bind(local_path)
|
||||
ctrl_socket.connect(str(socket_path))
|
||||
self._socket = ctrl_socket
|
||||
self._local_path = local_path
|
||||
self._connected = True
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._socket is not None:
|
||||
self._socket.close()
|
||||
if self._local_path is not None:
|
||||
try:
|
||||
Path(self._local_path).unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
self._socket = None
|
||||
self._local_path = None
|
||||
self._connected = False
|
||||
|
||||
def set_socket_for_testing(self, socket_obj: Any) -> None:
|
||||
"""Install a prebuilt socket object for tests."""
|
||||
self._socket = socket_obj
|
||||
self._connected = True
|
||||
|
||||
async def _execute(self, command: str, parse_kv: bool = False) -> CommandResult:
|
||||
await self.connect()
|
||||
assert self._socket is not None
|
||||
await asyncio.to_thread(self._socket.send, f"{command}\n".encode("utf-8"))
|
||||
|
||||
lines: list[str] = []
|
||||
terminal = "OK"
|
||||
while True:
|
||||
line = await asyncio.to_thread(self._socket.recv, 4096)
|
||||
if not line:
|
||||
terminal = "FAIL"
|
||||
break
|
||||
chunks = [part.strip() for part in line.decode("utf-8", errors="replace").splitlines()]
|
||||
for text in chunks:
|
||||
if not text:
|
||||
continue
|
||||
if text == "OK":
|
||||
terminal = "OK"
|
||||
break
|
||||
if text == "FAIL":
|
||||
terminal = "FAIL"
|
||||
break
|
||||
if text.startswith("UNKNOWN COMMAND"):
|
||||
terminal = "UNKNOWN COMMAND"
|
||||
break
|
||||
lines.append(text)
|
||||
if terminal != "OK" or any(chunk == "OK" for chunk in chunks):
|
||||
break
|
||||
|
||||
execution = CommandExecutionResult(
|
||||
execution_status=(
|
||||
"succeeded"
|
||||
if terminal == "OK"
|
||||
else (
|
||||
"unsupported"
|
||||
if terminal.startswith("UNKNOWN COMMAND")
|
||||
else "failed"
|
||||
)
|
||||
),
|
||||
execution_error_code=(
|
||||
None if terminal == "OK" else terminal.lower().replace(" ", "_")
|
||||
),
|
||||
execution_error_message=None if terminal == "OK" else terminal,
|
||||
)
|
||||
if execution.execution_status == "succeeded":
|
||||
if not lines:
|
||||
returned = CommandReturnedData(data_type="none", payload=None)
|
||||
elif parse_kv:
|
||||
returned = CommandReturnedData(
|
||||
data_type="kv", payload=_kv_payload("\n".join(lines))
|
||||
)
|
||||
else:
|
||||
returned = CommandReturnedData(
|
||||
data_type="text", payload="\n".join(lines)
|
||||
)
|
||||
else:
|
||||
returned = CommandReturnedData(data_type="none", payload=None)
|
||||
return CommandResult(
|
||||
command_id="",
|
||||
destination="ctrl_iface",
|
||||
execution=execution,
|
||||
returned_data=returned,
|
||||
)
|
||||
|
||||
async def status(self) -> CommandResult:
|
||||
return await self._execute("STATUS", parse_kv=True)
|
||||
|
||||
async def status_verbose(self) -> CommandResult:
|
||||
return await self._execute("STATUS-VERBOSE", parse_kv=True)
|
||||
|
||||
async def reassociate(self) -> CommandResult:
|
||||
return await self._execute("REASSOCIATE")
|
||||
|
||||
async def reconnect(self) -> CommandResult:
|
||||
return await self._execute("RECONNECT")
|
||||
|
||||
async def disconnect(self) -> CommandResult:
|
||||
return await self._execute("DISCONNECT")
|
||||
|
||||
async def scan(self) -> CommandResult:
|
||||
return await self._execute("SCAN")
|
||||
|
||||
async def scan_results(self) -> CommandResult:
|
||||
return await self._execute("SCAN_RESULTS")
|
||||
|
||||
async def bss(self, selector: str | None = None) -> CommandResult:
|
||||
command = "BSS" if selector in {None, ""} else f"BSS {selector}"
|
||||
return await self._execute(command)
|
||||
|
||||
async def attach(self) -> CommandResult:
|
||||
return await self._execute("ATTACH")
|
||||
|
||||
async def detach(self) -> CommandResult:
|
||||
return await self._execute("DETACH")
|
||||
|
||||
async def reconfigure(self) -> CommandResult:
|
||||
return await self._execute("RECONFIGURE")
|
||||
|
||||
async def terminate(self) -> CommandResult:
|
||||
return await self._execute("TERMINATE")
|
||||
|
||||
async def execute_command(
|
||||
self, command: str, parse_kv: bool = False
|
||||
) -> CommandResult:
|
||||
return await self._execute(command, parse_kv=parse_kv)
|
||||
|
||||
|
||||
class DbusCommandClient:
|
||||
def __init__(
|
||||
self,
|
||||
service: str,
|
||||
root_path: str,
|
||||
interface_name: str,
|
||||
bus_type: str = "system",
|
||||
) -> None:
|
||||
self.service = service
|
||||
self.root_path = root_path
|
||||
self.interface_name = interface_name
|
||||
self.bus_type = bus_type
|
||||
self._bus = None
|
||||
self._root_proxy = None
|
||||
self._connected = False
|
||||
self._interface_proxy_cache: dict[str, Any] = {}
|
||||
|
||||
async def connect(self) -> None:
|
||||
if self._connected:
|
||||
return
|
||||
bus_type = BusType.SYSTEM if self.bus_type == "system" else BusType.SESSION
|
||||
self._bus = MessageBus(bus_type=bus_type)
|
||||
await self._bus.connect()
|
||||
self._connected = True
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._bus is not None:
|
||||
self._bus.disconnect()
|
||||
self._connected = False
|
||||
|
||||
async def _root_interface(self) -> Any:
|
||||
if self._bus is None:
|
||||
await self.connect()
|
||||
assert self._bus is not None
|
||||
if self._root_proxy is None:
|
||||
introspection = await self._bus.introspect(self.service, self.root_path)
|
||||
self._root_proxy = self._bus.get_proxy_object(
|
||||
self.service, self.root_path, introspection
|
||||
)
|
||||
return self._root_proxy.get_interface(self.service)
|
||||
|
||||
async def _interface_proxy(self, ifname: str) -> Any:
|
||||
cached = self._interface_proxy_cache.get(ifname)
|
||||
if cached is not None:
|
||||
return cached
|
||||
root_iface = await self._root_interface()
|
||||
interface_path = await getattr(root_iface, "GetInterface")(ifname)
|
||||
assert self._bus is not None
|
||||
introspection = await self._bus.introspect(self.service, interface_path)
|
||||
proxy = self._bus.get_proxy_object(self.service, interface_path, introspection)
|
||||
self._interface_proxy_cache[ifname] = proxy
|
||||
return proxy.get_interface(self.interface_name)
|
||||
|
||||
async def _interface_proxy_from_path(self, interface_path: str) -> Any:
|
||||
assert self._bus is not None
|
||||
introspection = await self._bus.introspect(self.service, interface_path)
|
||||
proxy = self._bus.get_proxy_object(self.service, interface_path, introspection)
|
||||
return proxy.get_interface(self.interface_name)
|
||||
|
||||
async def _call_root(
|
||||
self, command_id: str, method: str, *args: Any
|
||||
) -> CommandResult:
|
||||
try:
|
||||
root_iface = await self._root_interface()
|
||||
result = await getattr(root_iface, method)(*args)
|
||||
return CommandResult(
|
||||
command_id=command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult("succeeded"),
|
||||
returned_data=CommandReturnedData(
|
||||
"structured", json_safe(result) if result is not None else None
|
||||
),
|
||||
)
|
||||
except Exception as exc:
|
||||
return CommandResult(
|
||||
command_id=command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult(
|
||||
"failed",
|
||||
execution_error_code="dbus_error",
|
||||
execution_error_message=str(exc),
|
||||
),
|
||||
returned_data=CommandReturnedData("none", None),
|
||||
)
|
||||
|
||||
async def _call_interface(
|
||||
self, command_id: str, ifname: str, method: str, *args: Any
|
||||
) -> CommandResult:
|
||||
try:
|
||||
iface = await self._interface_proxy(ifname)
|
||||
result = await getattr(iface, method)(*args)
|
||||
return CommandResult(
|
||||
command_id=command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult("succeeded"),
|
||||
returned_data=CommandReturnedData(
|
||||
"structured", json_safe(result) if result is not None else None
|
||||
),
|
||||
)
|
||||
except Exception as exc:
|
||||
return CommandResult(
|
||||
command_id=command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult(
|
||||
"failed",
|
||||
execution_error_code="dbus_error",
|
||||
execution_error_message=str(exc),
|
||||
),
|
||||
returned_data=CommandReturnedData("none", None),
|
||||
)
|
||||
|
||||
async def create_interface(self, args: dict[str, Any]) -> CommandResult:
|
||||
return await self._call_root("", "CreateInterface", args)
|
||||
|
||||
async def remove_interface(self, interface_path: str) -> CommandResult:
|
||||
return await self._call_root("", "RemoveInterface", interface_path)
|
||||
|
||||
async def get_interface(self, ifname: str) -> CommandResult:
|
||||
return await self._call_root("", "GetInterface", ifname)
|
||||
|
||||
async def scan(self, args: dict[str, Any]) -> CommandResult:
|
||||
ifname = self._extract_ifname(args)
|
||||
return await self._call_interface("", ifname, "Scan", args)
|
||||
|
||||
async def disconnect(self, ifname: str | None = None) -> CommandResult:
|
||||
return await self._call_interface(
|
||||
"", self._require_ifname(ifname), "Disconnect"
|
||||
)
|
||||
|
||||
async def add_network(self, args: dict[str, Any]) -> CommandResult:
|
||||
ifname = self._extract_ifname(args)
|
||||
return await self._call_interface("", ifname, "AddNetwork", args)
|
||||
|
||||
async def remove_network(self, network_path: str, ifname: str) -> CommandResult:
|
||||
return await self._call_interface("", ifname, "RemoveNetwork", network_path)
|
||||
|
||||
async def remove_all_networks(self, ifname: str) -> CommandResult:
|
||||
return await self._call_interface("", ifname, "RemoveAllNetworks")
|
||||
|
||||
async def select_network(self, network_path: str, ifname: str) -> CommandResult:
|
||||
return await self._call_interface("", ifname, "SelectNetwork", network_path)
|
||||
|
||||
async def reassociate(self, ifname: str) -> CommandResult:
|
||||
return await self._call_interface("", ifname, "Reassociate")
|
||||
|
||||
async def reattach(self, ifname: str) -> CommandResult:
|
||||
return await self._call_interface("", ifname, "Reattach")
|
||||
|
||||
async def reconnect(self, ifname: str) -> CommandResult:
|
||||
return await self._call_interface("", ifname, "Reconnect")
|
||||
|
||||
def _extract_ifname(self, args: Mapping[str, Any]) -> str:
|
||||
if "ifname" in args and isinstance(args["ifname"], str):
|
||||
return args["ifname"]
|
||||
if "interface" in args and isinstance(args["interface"], str):
|
||||
return args["interface"]
|
||||
if "interface_name" in args and isinstance(args["interface_name"], str):
|
||||
return args["interface_name"]
|
||||
raise ValueError("missing interface name for D-Bus command")
|
||||
|
||||
def _require_ifname(self, ifname: str | None) -> str:
|
||||
if not ifname:
|
||||
raise ValueError("missing interface name for D-Bus command")
|
||||
return ifname
|
||||
|
||||
async def call_endpoint(
|
||||
self, command_id: str, endpoint: CommandEndpoint, arguments: Mapping[str, Any]
|
||||
) -> CommandResult:
|
||||
if endpoint.object == self.service and endpoint.method in {
|
||||
"CreateInterface",
|
||||
"RemoveInterface",
|
||||
"GetInterface",
|
||||
}:
|
||||
root_iface = await self._root_interface()
|
||||
method = getattr(root_iface, endpoint.method)
|
||||
if endpoint.method == "CreateInterface":
|
||||
result = await method(dict(arguments))
|
||||
elif endpoint.method == "RemoveInterface":
|
||||
interface_path = (
|
||||
arguments.get("interface_path")
|
||||
or arguments.get("path")
|
||||
or arguments.get("interface")
|
||||
)
|
||||
if not isinstance(interface_path, str):
|
||||
raise ValueError(
|
||||
"RemoveInterface requires interface_path/path/interface"
|
||||
)
|
||||
result = await method(interface_path)
|
||||
else:
|
||||
ifname = arguments.get("ifname") or arguments.get("interface_name")
|
||||
if not isinstance(ifname, str):
|
||||
raise ValueError("GetInterface requires ifname/interface_name")
|
||||
result = await method(ifname)
|
||||
return CommandResult(
|
||||
command_id=command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult("succeeded"),
|
||||
returned_data=CommandReturnedData(
|
||||
"structured", json_safe(result) if result is not None else None
|
||||
),
|
||||
)
|
||||
|
||||
if "interface_path" in arguments and isinstance(
|
||||
arguments["interface_path"], str
|
||||
):
|
||||
iface = await self._interface_proxy_from_path(arguments["interface_path"])
|
||||
else:
|
||||
ifname = self._extract_ifname(arguments)
|
||||
iface = await self._interface_proxy(ifname)
|
||||
method = getattr(iface, endpoint.method)
|
||||
if endpoint.method in {"Scan", "AddNetwork"}:
|
||||
result = await method(dict(arguments))
|
||||
elif endpoint.method in {"RemoveNetwork", "SelectNetwork"}:
|
||||
target = arguments.get("network_path") or arguments.get("network")
|
||||
if not isinstance(target, str):
|
||||
raise ValueError(f"{endpoint.method} requires network_path/network")
|
||||
result = await method(target)
|
||||
else:
|
||||
result = await method()
|
||||
return CommandResult(
|
||||
command_id=command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult("succeeded"),
|
||||
returned_data=CommandReturnedData(
|
||||
"structured", json_safe(result) if result is not None else None
|
||||
),
|
||||
)
|
||||
|
||||
async def dispatch_logical(
|
||||
self,
|
||||
command_id: str,
|
||||
logical_name: str,
|
||||
endpoint: CommandEndpoint,
|
||||
arguments: Mapping[str, Any],
|
||||
) -> CommandResult:
|
||||
return await self.call_endpoint(command_id, endpoint, arguments)
|
||||
|
||||
|
||||
class CommandDispatcher:
|
||||
def __init__(
|
||||
self,
|
||||
config: AppConfig,
|
||||
dbus_client: DbusCommandClientProtocol | None = None,
|
||||
ctrl_iface_client: CtrlIfaceCommandClientProtocol | None = None,
|
||||
) -> None:
|
||||
self._config = config
|
||||
self._dbus_client = dbus_client or DbusCommandClient(
|
||||
service=config.dbus.service,
|
||||
root_path=config.dbus.root_path,
|
||||
interface_name=config.dbus.interface_name,
|
||||
bus_type=config.dbus.bus,
|
||||
)
|
||||
self._ctrl_iface_client = ctrl_iface_client or CtrlIfaceCommandClient(
|
||||
config.ctrl_iface.socket_path
|
||||
)
|
||||
|
||||
def select_destination(self, request: CommandRequest) -> str:
|
||||
destination = _destination_name(request.destination_hint)
|
||||
if destination not in {"dbus", "ctrl_iface"}:
|
||||
return "unsupported"
|
||||
return destination
|
||||
|
||||
async def dispatch(self, request: CommandRequest) -> CommandResult:
|
||||
destination = self.select_destination(request)
|
||||
if destination == "unsupported":
|
||||
return CommandResult(
|
||||
command_id=request.command_id,
|
||||
destination="unsupported",
|
||||
execution=CommandExecutionResult(
|
||||
execution_status="unsupported",
|
||||
execution_error_code="unsupported_destination",
|
||||
execution_error_message="destination must be explicitly configured",
|
||||
),
|
||||
returned_data=CommandReturnedData("none", None),
|
||||
)
|
||||
|
||||
if destination == "ctrl_iface":
|
||||
return await self._dispatch_ctrl_iface(request)
|
||||
return await self._dispatch_dbus(request)
|
||||
|
||||
async def _dispatch_ctrl_iface(self, request: CommandRequest) -> CommandResult:
|
||||
if not self._config.commands.ctrl_iface.enabled:
|
||||
return CommandResult(
|
||||
command_id=request.command_id,
|
||||
destination="ctrl_iface",
|
||||
execution=CommandExecutionResult(
|
||||
execution_status="unsupported",
|
||||
execution_error_code="destination_disabled",
|
||||
execution_error_message="ctrl_iface destination is disabled",
|
||||
),
|
||||
returned_data=CommandReturnedData("none", None),
|
||||
)
|
||||
mapping = self._config.commands.ctrl_iface.commands.get(request.command_kind)
|
||||
if mapping is None:
|
||||
return CommandResult(
|
||||
command_id=request.command_id,
|
||||
destination="ctrl_iface",
|
||||
execution=CommandExecutionResult(
|
||||
execution_status="unsupported",
|
||||
execution_error_code="unsupported_command",
|
||||
execution_error_message=f"unknown ctrl_iface command kind {request.command_kind!r}",
|
||||
),
|
||||
returned_data=CommandReturnedData("none", None),
|
||||
)
|
||||
|
||||
client = self._ctrl_iface_client
|
||||
if not client._connected:
|
||||
await client.connect()
|
||||
parse_kv = mapping in {"STATUS", "STATUS-VERBOSE"}
|
||||
result = await client.execute_command(mapping, parse_kv=parse_kv)
|
||||
result.command_id = request.command_id
|
||||
result.destination = "ctrl_iface"
|
||||
return result
|
||||
|
||||
async def _dispatch_dbus(self, request: CommandRequest) -> CommandResult:
|
||||
if not self._config.commands.dbus.enabled:
|
||||
return CommandResult(
|
||||
command_id=request.command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult(
|
||||
execution_status="unsupported",
|
||||
execution_error_code="destination_disabled",
|
||||
execution_error_message="dbus destination is disabled",
|
||||
),
|
||||
returned_data=CommandReturnedData("none", None),
|
||||
)
|
||||
endpoint = self._config.commands.dbus.methods.get(request.command_kind)
|
||||
if endpoint is None:
|
||||
return CommandResult(
|
||||
command_id=request.command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult(
|
||||
execution_status="unsupported",
|
||||
execution_error_code="unsupported_command",
|
||||
execution_error_message=f"unknown dbus command kind {request.command_kind!r}",
|
||||
),
|
||||
returned_data=CommandReturnedData("none", None),
|
||||
)
|
||||
client = self._dbus_client
|
||||
if not client._connected:
|
||||
await client.connect()
|
||||
result = await client.call_endpoint(
|
||||
request.command_id, endpoint, request.arguments
|
||||
)
|
||||
result.command_id = request.command_id
|
||||
result.destination = "dbus"
|
||||
return result
|
||||
|
|
@ -0,0 +1,312 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
import yaml
|
||||
|
||||
from .models import (
|
||||
AppConfig,
|
||||
CommandsConfig,
|
||||
CommandsDispatchConfig,
|
||||
CommandEndpoint,
|
||||
CtrlIfaceCommandsConfig,
|
||||
CtrlIfaceSourceConfig,
|
||||
DbusCommandsConfig,
|
||||
DbusSourceConfig,
|
||||
EventClassifierRule,
|
||||
GuardsConfig,
|
||||
ObservabilityConfig,
|
||||
OutputConfig,
|
||||
RuntimeConfig,
|
||||
RuntimeSourceConfig,
|
||||
SourceConfigBundle,
|
||||
SourceFilterRule,
|
||||
TriggerRule,
|
||||
)
|
||||
|
||||
|
||||
def _ensure_mapping(value: Any, context: str) -> Mapping[str, Any]:
|
||||
if not isinstance(value, Mapping):
|
||||
raise ValueError(f"{context} must be a mapping")
|
||||
return value
|
||||
|
||||
|
||||
def _ensure_list(value: Any, context: str) -> list[Any]:
|
||||
if not isinstance(value, list):
|
||||
raise ValueError(f"{context} must be a list")
|
||||
return value
|
||||
|
||||
|
||||
def _ensure_bool(value: Any, context: str) -> bool:
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{context} must be a boolean")
|
||||
return value
|
||||
|
||||
|
||||
def _ensure_int(value: Any, context: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{context} must be an integer")
|
||||
return value
|
||||
|
||||
|
||||
def _ensure_str(value: Any, context: str) -> str:
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{context} must be a string")
|
||||
return value
|
||||
|
||||
|
||||
def _load_yaml_document(source: str | Path | Mapping[str, Any]) -> Mapping[str, Any]:
|
||||
if isinstance(source, Mapping):
|
||||
return source
|
||||
if isinstance(source, Path):
|
||||
text = source.read_text(encoding="utf-8")
|
||||
data = yaml.safe_load(text)
|
||||
return _ensure_mapping(data, "configuration")
|
||||
if isinstance(source, str) and "\n" not in source:
|
||||
try:
|
||||
path = Path(source)
|
||||
if path.exists():
|
||||
text = path.read_text(encoding="utf-8")
|
||||
data = yaml.safe_load(text)
|
||||
return _ensure_mapping(data, "configuration")
|
||||
except OSError:
|
||||
pass
|
||||
data = yaml.safe_load(source)
|
||||
return _ensure_mapping(data, "configuration")
|
||||
|
||||
|
||||
def _parse_filter_rule(value: Any, context: str) -> SourceFilterRule:
|
||||
data = _ensure_mapping(value, context)
|
||||
return SourceFilterRule(
|
||||
rule_id=_ensure_str(data["id"], f"{context}.id"),
|
||||
enabled=_ensure_bool(data.get("enabled", True), f"{context}.enabled"),
|
||||
match=dict(_ensure_mapping(data.get("match", {}), f"{context}.match")),
|
||||
action=_ensure_str(data["action"], f"{context}.action"),
|
||||
)
|
||||
|
||||
|
||||
def _parse_classifier_rule(value: Any, context: str) -> EventClassifierRule:
|
||||
data = _ensure_mapping(value, context)
|
||||
disposition = _ensure_str(data["disposition"], f"{context}.disposition")
|
||||
if disposition not in {"drop", "serialize_only", "serialize_and_trigger"}:
|
||||
raise ValueError(f"{context}.disposition has unsupported value {disposition!r}")
|
||||
return EventClassifierRule(
|
||||
rule_id=_ensure_str(data["id"], f"{context}.id"),
|
||||
enabled=_ensure_bool(data.get("enabled", True), f"{context}.enabled"),
|
||||
match=dict(_ensure_mapping(data.get("match", {}), f"{context}.match")),
|
||||
disposition=disposition,
|
||||
)
|
||||
|
||||
|
||||
def _parse_trigger_rule(value: Any, context: str) -> TriggerRule:
|
||||
data = _ensure_mapping(value, context)
|
||||
command = _ensure_mapping(data["command"], f"{context}.command")
|
||||
return TriggerRule(
|
||||
rule_id=_ensure_str(data["id"], f"{context}.id"),
|
||||
enabled=_ensure_bool(data.get("enabled", True), f"{context}.enabled"),
|
||||
match=dict(_ensure_mapping(data.get("match", {}), f"{context}.match")),
|
||||
command=dict(command),
|
||||
cooldown_ms=_ensure_int(data.get("cooldown_ms", 0), f"{context}.cooldown_ms"),
|
||||
max_retries=_ensure_int(data.get("max_retries", 0), f"{context}.max_retries"),
|
||||
)
|
||||
|
||||
|
||||
def _parse_runtime_config(value: Any) -> RuntimeConfig:
|
||||
data = _ensure_mapping(value, "runtime")
|
||||
generate_events = _ensure_mapping(
|
||||
data.get("generate_events", {}), "runtime.generate_events"
|
||||
)
|
||||
timers = _ensure_mapping(data.get("timers", {}), "runtime.timers")
|
||||
return RuntimeConfig(
|
||||
generate_start=_ensure_bool(
|
||||
generate_events.get("start", True), "runtime.generate_events.start"
|
||||
),
|
||||
generate_reload=_ensure_bool(
|
||||
generate_events.get("reload", True), "runtime.generate_events.reload"
|
||||
),
|
||||
generate_stop=_ensure_bool(
|
||||
generate_events.get("stop", True), "runtime.generate_events.stop"
|
||||
),
|
||||
generate_timer_tick=_ensure_bool(
|
||||
generate_events.get("timer_tick", True),
|
||||
"runtime.generate_events.timer_tick",
|
||||
),
|
||||
timer_tick_interval_ms=_ensure_int(
|
||||
timers.get("timer_tick_interval_ms", 100),
|
||||
"runtime.timers.timer_tick_interval_ms",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _parse_dbus_source_config(value: Any) -> DbusSourceConfig:
|
||||
data = _ensure_mapping(value, "sources.dbus")
|
||||
filters = [
|
||||
_parse_filter_rule(item, f"sources.dbus.filters[{index}]")
|
||||
for index, item in enumerate(
|
||||
_ensure_list(data.get("filters", []), "sources.dbus.filters")
|
||||
)
|
||||
]
|
||||
return DbusSourceConfig(
|
||||
enabled=_ensure_bool(data.get("enabled", True), "sources.dbus.enabled"),
|
||||
bus=_ensure_str(data.get("bus", "system"), "sources.dbus.bus"),
|
||||
service=_ensure_str(data["service"], "sources.dbus.service"),
|
||||
root_path=_ensure_str(data["root_path"], "sources.dbus.root_path"),
|
||||
interface_name=_ensure_str(
|
||||
data["interface_name"], "sources.dbus.interface_name"
|
||||
),
|
||||
filters=filters,
|
||||
)
|
||||
|
||||
|
||||
def _parse_ctrl_iface_source_config(value: Any) -> CtrlIfaceSourceConfig:
|
||||
data = _ensure_mapping(value, "sources.ctrl_iface")
|
||||
filters = [
|
||||
_parse_filter_rule(item, f"sources.ctrl_iface.filters[{index}]")
|
||||
for index, item in enumerate(
|
||||
_ensure_list(data.get("filters", []), "sources.ctrl_iface.filters")
|
||||
)
|
||||
]
|
||||
return CtrlIfaceSourceConfig(
|
||||
enabled=_ensure_bool(data.get("enabled", True), "sources.ctrl_iface.enabled"),
|
||||
socket_path=_ensure_str(data["socket_path"], "sources.ctrl_iface.socket_path"),
|
||||
attach_for_events=_ensure_bool(
|
||||
data.get("attach_for_events", True), "sources.ctrl_iface.attach_for_events"
|
||||
),
|
||||
filters=filters,
|
||||
)
|
||||
|
||||
|
||||
def _parse_runtime_source_config(value: Any) -> RuntimeSourceConfig:
|
||||
data = _ensure_mapping(value, "sources.runtime")
|
||||
filters = [
|
||||
_parse_filter_rule(item, f"sources.runtime.filters[{index}]")
|
||||
for index, item in enumerate(
|
||||
_ensure_list(data.get("filters", []), "sources.runtime.filters")
|
||||
)
|
||||
]
|
||||
return RuntimeSourceConfig(
|
||||
enabled=_ensure_bool(data.get("enabled", True), "sources.runtime.enabled"),
|
||||
filters=filters,
|
||||
)
|
||||
|
||||
|
||||
def _parse_commands_config(value: Any) -> CommandsConfig:
|
||||
data = _ensure_mapping(value, "commands")
|
||||
dispatch = _ensure_mapping(data.get("dispatch", {}), "commands.dispatch")
|
||||
dbus = _ensure_mapping(data.get("dbus", {}), "commands.dbus")
|
||||
ctrl_iface = _ensure_mapping(data.get("ctrl_iface", {}), "commands.ctrl_iface")
|
||||
|
||||
dbus_methods: dict[str, CommandEndpoint] = {}
|
||||
for logical_name, endpoint in _ensure_mapping(
|
||||
dbus.get("methods", {}), "commands.dbus.methods"
|
||||
).items():
|
||||
endpoint_data = _ensure_mapping(
|
||||
endpoint, f"commands.dbus.methods.{logical_name}"
|
||||
)
|
||||
dbus_methods[str(logical_name)] = CommandEndpoint(
|
||||
object=_ensure_str(
|
||||
endpoint_data["object"], f"commands.dbus.methods.{logical_name}.object"
|
||||
),
|
||||
method=_ensure_str(
|
||||
endpoint_data["method"], f"commands.dbus.methods.{logical_name}.method"
|
||||
),
|
||||
)
|
||||
|
||||
ctrl_commands: dict[str, str] = {}
|
||||
for logical_name, command in _ensure_mapping(
|
||||
ctrl_iface.get("commands", {}), "commands.ctrl_iface.commands"
|
||||
).items():
|
||||
ctrl_commands[str(logical_name)] = _ensure_str(
|
||||
command, f"commands.ctrl_iface.commands.{logical_name}"
|
||||
)
|
||||
|
||||
return CommandsConfig(
|
||||
dispatch=CommandsDispatchConfig(
|
||||
strategy=_ensure_str(
|
||||
dispatch.get("strategy", "explicit_destination_only"),
|
||||
"commands.dispatch.strategy",
|
||||
),
|
||||
),
|
||||
dbus=DbusCommandsConfig(
|
||||
enabled=_ensure_bool(dbus.get("enabled", True), "commands.dbus.enabled"),
|
||||
methods=dbus_methods,
|
||||
),
|
||||
ctrl_iface=CtrlIfaceCommandsConfig(
|
||||
enabled=_ensure_bool(
|
||||
ctrl_iface.get("enabled", True), "commands.ctrl_iface.enabled"
|
||||
),
|
||||
commands=ctrl_commands,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _parse_observability_config(value: Any) -> ObservabilityConfig:
|
||||
data = _ensure_mapping(value, "observability")
|
||||
return ObservabilityConfig(
|
||||
emit_internal_metrics=_ensure_bool(
|
||||
data.get("emit_internal_metrics", True),
|
||||
"observability.emit_internal_metrics",
|
||||
),
|
||||
log_level=_ensure_str(data.get("log_level", "info"), "observability.log_level"),
|
||||
)
|
||||
|
||||
|
||||
def _parse_guards_config(value: Any) -> GuardsConfig:
|
||||
data = _ensure_mapping(value, "guards")
|
||||
trigger_loop_guard = _ensure_mapping(
|
||||
data.get("trigger_loop_guard", {}), "guards.trigger_loop_guard"
|
||||
)
|
||||
return GuardsConfig(trigger_loop_guard=dict(trigger_loop_guard))
|
||||
|
||||
|
||||
def load_app_config(source: str | Path | Mapping[str, Any]) -> AppConfig:
|
||||
data = _load_yaml_document(source)
|
||||
version = _ensure_int(data.get("version", 1), "version")
|
||||
if version != 1:
|
||||
raise ValueError(f"unsupported configuration version: {version}")
|
||||
|
||||
runtime = _parse_runtime_config(data.get("runtime", {}))
|
||||
sources = _ensure_mapping(data.get("sources", {}), "sources")
|
||||
classifier_section = _ensure_mapping(data.get("classifier", {}), "classifier")
|
||||
trigger_section = _ensure_mapping(data.get("triggers", {}), "triggers")
|
||||
output_section = _ensure_mapping(data.get("output", {}), "output")
|
||||
classifier_rules = [
|
||||
_parse_classifier_rule(item, f"classifier.rules[{index}]")
|
||||
for index, item in enumerate(
|
||||
_ensure_list(classifier_section.get("rules", []), "classifier.rules")
|
||||
)
|
||||
]
|
||||
trigger_rules = [
|
||||
_parse_trigger_rule(item, f"triggers.rules[{index}]")
|
||||
for index, item in enumerate(
|
||||
_ensure_list(trigger_section.get("rules", []), "triggers.rules")
|
||||
)
|
||||
]
|
||||
return AppConfig(
|
||||
version=version,
|
||||
runtime=runtime,
|
||||
sources=SourceConfigBundle(
|
||||
dbus=_parse_dbus_source_config(sources.get("dbus", {})),
|
||||
ctrl_iface=_parse_ctrl_iface_source_config(sources.get("ctrl_iface", {})),
|
||||
runtime=_parse_runtime_source_config(sources.get("runtime", {})),
|
||||
),
|
||||
classifier_rules=classifier_rules,
|
||||
trigger_rules=trigger_rules,
|
||||
commands=_parse_commands_config(data.get("commands", {})),
|
||||
output=OutputConfig(
|
||||
format=_ensure_str(output_section.get("format", "ndjson"), "output.format"),
|
||||
target=_ensure_str(output_section.get("target", "stdout"), "output.target"),
|
||||
flush_every_event=_ensure_bool(
|
||||
output_section.get("flush_every_event", True),
|
||||
"output.flush_every_event",
|
||||
),
|
||||
),
|
||||
observability=_parse_observability_config(data.get("observability", {})),
|
||||
guards=_parse_guards_config(data.get("guards", {})),
|
||||
)
|
||||
|
||||
|
||||
def clone_with_runtime(config: AppConfig, runtime: RuntimeConfig) -> AppConfig:
|
||||
return replace(config, runtime=runtime)
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from .services import Observability
|
||||
|
||||
|
||||
class AppLifecycleService:
|
||||
def __init__(
|
||||
self, runtime_source, observability: Observability | None = None
|
||||
) -> None:
|
||||
self._runtime_source = runtime_source
|
||||
self._observability = observability
|
||||
|
||||
async def start(self) -> None:
|
||||
await self._runtime_source.start()
|
||||
if getattr(self._runtime_source, "_config", None) is not None and getattr(
|
||||
self._runtime_source._config, "generate_start", True
|
||||
):
|
||||
await self._runtime_source.emit_start()
|
||||
|
||||
async def reload(self) -> None:
|
||||
if getattr(self._runtime_source, "_config", None) is not None and getattr(
|
||||
self._runtime_source._config, "generate_reload", True
|
||||
):
|
||||
await self._runtime_source.emit_reload()
|
||||
|
||||
async def stop(self) -> None:
|
||||
if getattr(self._runtime_source, "_config", None) is not None and getattr(
|
||||
self._runtime_source._config, "generate_stop", True
|
||||
):
|
||||
await self._runtime_source.emit_stop()
|
||||
await self._runtime_source.stop()
|
||||
|
|
@ -0,0 +1,265 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field, fields, is_dataclass
|
||||
from enum import Enum
|
||||
from typing import Any, Mapping
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def _to_json_safe(value: Any) -> Any:
|
||||
if is_dataclass(value) and not isinstance(value, type):
|
||||
return {
|
||||
item.name: _to_json_safe(getattr(value, item.name))
|
||||
for item in fields(value)
|
||||
}
|
||||
if isinstance(value, Mapping):
|
||||
return {str(key): _to_json_safe(val) for key, val in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [_to_json_safe(item) for item in value]
|
||||
if isinstance(value, set):
|
||||
return [_to_json_safe(item) for item in sorted(value, key=repr)]
|
||||
if isinstance(value, Enum):
|
||||
return _to_json_safe(value.value)
|
||||
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
def json_safe(value: Any) -> Any:
|
||||
return _to_json_safe(value)
|
||||
|
||||
|
||||
def new_event_id(prefix: str = "e") -> str:
|
||||
return f"{prefix}-{uuid4().hex}"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RawSourceEvent:
|
||||
event_id: str
|
||||
source_type: str
|
||||
source_id: str
|
||||
observed_at_unix_ms: int
|
||||
raw_payload: object
|
||||
|
||||
def payload_mapping(self) -> dict[str, Any]:
|
||||
if isinstance(self.raw_payload, Mapping):
|
||||
return dict(self.raw_payload)
|
||||
return {}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class NormalizedEvent:
|
||||
event_id: str
|
||||
source_type: str
|
||||
source_id: str
|
||||
event_kind: str
|
||||
observed_at_unix_ms: int
|
||||
severity: str
|
||||
payload_raw: object
|
||||
payload_structured: dict[str, Any]
|
||||
correlation_id: str | None
|
||||
causation_id: str | None
|
||||
|
||||
def to_output_dict(self) -> dict[str, Any]:
|
||||
output = {
|
||||
"event_id": self.event_id,
|
||||
"source_type": self.source_type,
|
||||
"source_id": self.source_id,
|
||||
"event_kind": self.event_kind,
|
||||
"observed_at_unix_ms": self.observed_at_unix_ms,
|
||||
"severity": self.severity,
|
||||
"payload": _to_json_safe(self.payload_structured),
|
||||
}
|
||||
if self.correlation_id is not None:
|
||||
output["correlation_id"] = self.correlation_id
|
||||
if self.causation_id is not None:
|
||||
output["causation_id"] = self.causation_id
|
||||
return output
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class EventDisposition:
|
||||
action: str
|
||||
classifier_rule_id: str | None
|
||||
trigger_rule_ids: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CommandRequest:
|
||||
command_id: str
|
||||
command_kind: str
|
||||
destination_hint: str | None
|
||||
arguments: dict[str, Any]
|
||||
triggered_by_event_id: str | None
|
||||
correlation_id: str | None
|
||||
priority: str | None
|
||||
not_before_unix_ms: int | None
|
||||
expires_at_unix_ms: int | None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CommandExecutionResult:
|
||||
execution_status: str
|
||||
execution_error_code: str | None = None
|
||||
execution_error_message: str | None = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CommandReturnedData:
|
||||
data_type: str
|
||||
payload: object | None = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CommandResult:
|
||||
command_id: str
|
||||
destination: str
|
||||
execution: CommandExecutionResult
|
||||
returned_data: CommandReturnedData
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"command_id": self.command_id,
|
||||
"destination": self.destination,
|
||||
"execution": _to_json_safe(self.execution),
|
||||
"returned_data": _to_json_safe(self.returned_data),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CommandEndpoint:
|
||||
object: str
|
||||
method: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RuntimeConfig:
|
||||
generate_start: bool
|
||||
generate_reload: bool
|
||||
generate_stop: bool
|
||||
generate_timer_tick: bool
|
||||
timer_tick_interval_ms: int
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SourceFilterRule:
|
||||
rule_id: str
|
||||
enabled: bool
|
||||
match: dict[str, Any]
|
||||
action: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class DbusSourceConfig:
|
||||
enabled: bool
|
||||
bus: str
|
||||
service: str
|
||||
root_path: str
|
||||
interface_name: str
|
||||
filters: list[SourceFilterRule]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CtrlIfaceSourceConfig:
|
||||
enabled: bool
|
||||
socket_path: str
|
||||
attach_for_events: bool
|
||||
filters: list[SourceFilterRule]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RuntimeSourceConfig:
|
||||
enabled: bool
|
||||
filters: list[SourceFilterRule]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SourceConfigBundle:
|
||||
dbus: DbusSourceConfig
|
||||
ctrl_iface: CtrlIfaceSourceConfig
|
||||
runtime: RuntimeSourceConfig
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class EventClassifierRule:
|
||||
rule_id: str
|
||||
enabled: bool
|
||||
match: dict[str, Any]
|
||||
disposition: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TriggerRule:
|
||||
rule_id: str
|
||||
enabled: bool
|
||||
match: dict[str, Any]
|
||||
command: dict[str, Any]
|
||||
cooldown_ms: int
|
||||
max_retries: int
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class OutputConfig:
|
||||
format: str
|
||||
target: str
|
||||
flush_every_event: bool
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class DbusCommandsConfig:
|
||||
enabled: bool
|
||||
methods: dict[str, CommandEndpoint]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CtrlIfaceCommandsConfig:
|
||||
enabled: bool
|
||||
commands: dict[str, str]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CommandsDispatchConfig:
|
||||
strategy: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CommandsConfig:
|
||||
dispatch: CommandsDispatchConfig
|
||||
dbus: DbusCommandsConfig
|
||||
ctrl_iface: CtrlIfaceCommandsConfig
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ObservabilityConfig:
|
||||
emit_internal_metrics: bool
|
||||
log_level: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GuardsConfig:
|
||||
trigger_loop_guard: dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AppConfig:
|
||||
version: int
|
||||
runtime: RuntimeConfig
|
||||
sources: SourceConfigBundle
|
||||
classifier_rules: list[EventClassifierRule]
|
||||
trigger_rules: list[TriggerRule]
|
||||
commands: CommandsConfig
|
||||
output: OutputConfig
|
||||
observability: ObservabilityConfig
|
||||
guards: GuardsConfig
|
||||
|
||||
@property
|
||||
def dbus(self) -> DbusSourceConfig:
|
||||
return self.sources.dbus
|
||||
|
||||
@property
|
||||
def ctrl_iface(self) -> CtrlIfaceSourceConfig:
|
||||
return self.sources.ctrl_iface
|
||||
|
||||
@property
|
||||
def runtime_source(self) -> RuntimeSourceConfig:
|
||||
return self.sources.runtime
|
||||
|
|
@ -0,0 +1,488 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Mapping
|
||||
|
||||
from .models import (
|
||||
CommandRequest,
|
||||
CommandResult,
|
||||
EventDisposition,
|
||||
EventClassifierRule,
|
||||
NormalizedEvent,
|
||||
RawSourceEvent,
|
||||
SourceFilterRule,
|
||||
TriggerRule,
|
||||
json_safe,
|
||||
new_event_id,
|
||||
)
|
||||
from .services import Clock, CorrelationIdProvider, Observability
|
||||
from .protocols import (
|
||||
CommandDispatcherProtocol,
|
||||
EventPipelineProtocol,
|
||||
EventSourceProtocol,
|
||||
LifecycleServiceProtocol,
|
||||
)
|
||||
|
||||
|
||||
def _is_mapping(value: Any) -> bool:
|
||||
return isinstance(value, Mapping)
|
||||
|
||||
|
||||
def _mapping(value: Any) -> dict[str, Any]:
|
||||
if _is_mapping(value):
|
||||
return dict(value)
|
||||
return {}
|
||||
|
||||
|
||||
def _event_kind_from_payload(source_type: str, payload: Mapping[str, Any]) -> str:
|
||||
value = payload.get("event_kind")
|
||||
if isinstance(value, str) and value:
|
||||
return value
|
||||
if source_type == "dbus":
|
||||
member = payload.get("member") or payload.get("Member")
|
||||
if isinstance(member, str) and member:
|
||||
if "-" in member and member.upper() == member:
|
||||
return member
|
||||
value = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", member)
|
||||
value = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", value)
|
||||
return value.lower()
|
||||
return "dbus_event"
|
||||
if source_type == "ctrl_iface":
|
||||
line = payload.get("line") or payload.get("message")
|
||||
if isinstance(line, str) and line:
|
||||
return line.split()[0]
|
||||
return "ctrl_iface_event"
|
||||
if source_type == "runtime":
|
||||
runtime_kind = payload.get("runtime_event") or payload.get("kind")
|
||||
if isinstance(runtime_kind, str) and runtime_kind:
|
||||
return runtime_kind
|
||||
return "runtime_event"
|
||||
return "event"
|
||||
|
||||
|
||||
def _event_view_from_raw(
|
||||
event: RawSourceEvent,
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
payload = _mapping(event.raw_payload)
|
||||
view = {
|
||||
"event_id": event.event_id,
|
||||
"source_type": event.source_type,
|
||||
"source_id": event.source_id,
|
||||
"event_kind": _event_kind_from_payload(event.source_type, payload),
|
||||
"observed_at_unix_ms": event.observed_at_unix_ms,
|
||||
}
|
||||
view.update(payload)
|
||||
return view, payload
|
||||
|
||||
|
||||
def _event_view_from_normalized(
|
||||
event: NormalizedEvent,
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
payload = dict(event.payload_structured)
|
||||
view = {
|
||||
"event_id": event.event_id,
|
||||
"source_type": event.source_type,
|
||||
"source_id": event.source_id,
|
||||
"event_kind": event.event_kind,
|
||||
"observed_at_unix_ms": event.observed_at_unix_ms,
|
||||
"severity": event.severity,
|
||||
"correlation_id": event.correlation_id,
|
||||
"causation_id": event.causation_id,
|
||||
}
|
||||
view.update(payload)
|
||||
return view, payload
|
||||
|
||||
|
||||
def _match_values(candidate: Any, expected: Any) -> bool:
|
||||
if isinstance(expected, list):
|
||||
return any(_match_values(candidate, item) for item in expected)
|
||||
return candidate == expected
|
||||
|
||||
|
||||
def _matches_rule(
|
||||
match: Mapping[str, Any],
|
||||
event_view: Mapping[str, Any],
|
||||
payload_view: Mapping[str, Any],
|
||||
) -> bool:
|
||||
if match.get("any") is True:
|
||||
return True
|
||||
|
||||
for key, candidate in match.items():
|
||||
if key in {"any", "payload_has_any_key", "payload_has_all_keys"}:
|
||||
continue
|
||||
if key.endswith("_in"):
|
||||
actual_key = key[:-3]
|
||||
if actual_key not in event_view:
|
||||
return False
|
||||
if not _match_values(event_view.get(actual_key), candidate):
|
||||
return False
|
||||
continue
|
||||
if key in {"Interface", "Path", "Member"}:
|
||||
if not _match_values(event_view.get(key), candidate):
|
||||
return False
|
||||
continue
|
||||
if event_view.get(key) != candidate:
|
||||
return False
|
||||
|
||||
any_keys = match.get("payload_has_any_key")
|
||||
if any_keys is not None:
|
||||
if not isinstance(any_keys, list):
|
||||
raise ValueError("payload_has_any_key must be a list")
|
||||
if not any(key in payload_view for key in any_keys):
|
||||
return False
|
||||
|
||||
all_keys = match.get("payload_has_all_keys")
|
||||
if all_keys is not None:
|
||||
if not isinstance(all_keys, list):
|
||||
raise ValueError("payload_has_all_keys must be a list")
|
||||
if not all(key in payload_view for key in all_keys):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _keep_or_drop(action: str) -> bool:
|
||||
if action == "keep":
|
||||
return True
|
||||
if action == "drop":
|
||||
return False
|
||||
raise ValueError(f"unsupported source filter action: {action}")
|
||||
|
||||
|
||||
class SourceFilterChain:
|
||||
def __init__(
|
||||
self,
|
||||
rules_by_source: Mapping[str, list[SourceFilterRule]],
|
||||
observability: Observability | None = None,
|
||||
) -> None:
|
||||
self._rules_by_source = {
|
||||
key: list(value) for key, value in rules_by_source.items()
|
||||
}
|
||||
self._observability = observability
|
||||
|
||||
def apply(self, event: RawSourceEvent, source_type: str) -> bool:
|
||||
event_view, payload_view = _event_view_from_raw(event)
|
||||
for rule in self._rules_by_source.get(source_type, []):
|
||||
if not rule.enabled:
|
||||
continue
|
||||
if _matches_rule(rule.match, event_view, payload_view):
|
||||
return _keep_or_drop(rule.action)
|
||||
return True
|
||||
|
||||
|
||||
def _structured_payload(payload: object) -> dict[str, Any]:
|
||||
if isinstance(payload, Mapping):
|
||||
structured = dict(payload)
|
||||
for key in ("event_kind", "severity", "correlation_id", "causation_id"):
|
||||
structured.pop(key, None)
|
||||
return {key: json_safe(value) for key, value in structured.items()}
|
||||
if isinstance(payload, (str, int, float, bool)) or payload is None:
|
||||
return {"value": payload}
|
||||
return {"value": json_safe(payload)}
|
||||
|
||||
|
||||
class EventNormalizer:
|
||||
def __init__(
|
||||
self,
|
||||
clock: Clock | None = None,
|
||||
correlation_ids: CorrelationIdProvider | None = None,
|
||||
) -> None:
|
||||
self._clock = clock or Clock()
|
||||
self._correlation_ids = correlation_ids or CorrelationIdProvider()
|
||||
|
||||
def normalize(self, event: RawSourceEvent) -> NormalizedEvent:
|
||||
payload = _mapping(event.raw_payload)
|
||||
event_kind = _event_kind_from_payload(event.source_type, payload)
|
||||
severity = str(payload.get("severity", "info")) if payload else "info"
|
||||
correlation_id = payload.get("correlation_id") if payload else None
|
||||
causation_id = payload.get("causation_id") if payload else None
|
||||
if not isinstance(correlation_id, str):
|
||||
correlation_id = None
|
||||
if not isinstance(causation_id, str):
|
||||
causation_id = None
|
||||
structured = _structured_payload(payload if payload else event.raw_payload)
|
||||
return NormalizedEvent(
|
||||
event_id=event.event_id,
|
||||
source_type=event.source_type,
|
||||
source_id=event.source_id,
|
||||
event_kind=event_kind,
|
||||
observed_at_unix_ms=event.observed_at_unix_ms,
|
||||
severity=severity,
|
||||
payload_raw=event.raw_payload,
|
||||
payload_structured=structured,
|
||||
correlation_id=correlation_id,
|
||||
causation_id=causation_id,
|
||||
)
|
||||
|
||||
|
||||
class EventClassifier:
|
||||
def __init__(self, rules: list[EventClassifierRule]) -> None:
|
||||
self._rules = list(rules)
|
||||
|
||||
def classify(self, event: NormalizedEvent) -> EventDisposition:
|
||||
event_view, payload_view = _event_view_from_normalized(event)
|
||||
for rule in self._rules:
|
||||
if not rule.enabled:
|
||||
continue
|
||||
if _matches_rule(rule.match, event_view, payload_view):
|
||||
return EventDisposition(
|
||||
action=rule.disposition,
|
||||
classifier_rule_id=rule.rule_id,
|
||||
trigger_rule_ids=[],
|
||||
)
|
||||
return EventDisposition(
|
||||
action="drop", classifier_rule_id=None, trigger_rule_ids=[]
|
||||
)
|
||||
|
||||
|
||||
class NdjsonSerializer:
|
||||
def serialize(self, event: NormalizedEvent) -> str:
|
||||
return json.dumps(
|
||||
event.to_output_dict(), ensure_ascii=False, separators=(",", ":")
|
||||
)
|
||||
|
||||
|
||||
class StdoutOutputWriter:
|
||||
def __init__(self, stream: Any = None) -> None:
|
||||
self._stream = stream or sys.stdout
|
||||
|
||||
def write_line(self, line: str) -> None:
|
||||
self._stream.write(f"{line}\n")
|
||||
flush = getattr(self._stream, "flush", None)
|
||||
if callable(flush):
|
||||
flush()
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TriggerLoopGuard:
|
||||
default_cooldown_ms: int = 5000
|
||||
dedup_window_ms: int = 3000
|
||||
_last_fired: dict[tuple[str, str], int] = field(default_factory=dict)
|
||||
_last_rule_fire_at: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
def allow(
|
||||
self,
|
||||
event: NormalizedEvent,
|
||||
trigger_rule_id: str,
|
||||
now_unix_ms: int | None = None,
|
||||
cooldown_ms: int | None = None,
|
||||
) -> bool:
|
||||
now = now_unix_ms if now_unix_ms is not None else Clock().now_unix_ms()
|
||||
effective_cooldown = (
|
||||
self.default_cooldown_ms if cooldown_ms is None else cooldown_ms
|
||||
)
|
||||
last_rule_fire_at = self._last_rule_fire_at.get(trigger_rule_id)
|
||||
if (
|
||||
last_rule_fire_at is not None
|
||||
and now - last_rule_fire_at < effective_cooldown
|
||||
):
|
||||
return False
|
||||
key = (trigger_rule_id, self._event_signature(event))
|
||||
last = self._last_fired.get(key)
|
||||
if last is not None and now - last < self.dedup_window_ms:
|
||||
return False
|
||||
self._last_fired[key] = now
|
||||
self._last_rule_fire_at[trigger_rule_id] = now
|
||||
return True
|
||||
|
||||
def _event_signature(self, event: NormalizedEvent) -> str:
|
||||
payload = json.dumps(
|
||||
json_safe(event.payload_structured), sort_keys=True, ensure_ascii=False
|
||||
)
|
||||
return "|".join(
|
||||
[
|
||||
event.source_type,
|
||||
event.source_id,
|
||||
event.event_kind,
|
||||
payload,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class TriggerEngine:
|
||||
def __init__(
|
||||
self,
|
||||
rules: list[TriggerRule],
|
||||
loop_guard: TriggerLoopGuard,
|
||||
clock: Clock | None = None,
|
||||
) -> None:
|
||||
self._rules = list(rules)
|
||||
self._loop_guard = loop_guard
|
||||
self._clock = clock or Clock()
|
||||
|
||||
def evaluate(
|
||||
self, event: NormalizedEvent, disposition: EventDisposition
|
||||
) -> list[CommandRequest]:
|
||||
if disposition.action != "serialize_and_trigger":
|
||||
return []
|
||||
event_view, payload_view = _event_view_from_normalized(event)
|
||||
now = self._clock.now_unix_ms()
|
||||
requests: list[CommandRequest] = []
|
||||
for rule in self._rules:
|
||||
if not rule.enabled:
|
||||
continue
|
||||
if not _matches_rule(rule.match, event_view, payload_view):
|
||||
continue
|
||||
if not self._loop_guard.allow(
|
||||
event, rule.rule_id, now_unix_ms=now, cooldown_ms=rule.cooldown_ms
|
||||
):
|
||||
continue
|
||||
command = rule.command
|
||||
requests.append(
|
||||
CommandRequest(
|
||||
command_id=new_event_id("cmd"),
|
||||
command_kind=str(command["command_kind"]),
|
||||
destination_hint=str(command["destination"]),
|
||||
arguments=dict(command.get("arguments", {})),
|
||||
triggered_by_event_id=event.event_id,
|
||||
correlation_id=event.correlation_id,
|
||||
priority=command.get("priority"),
|
||||
not_before_unix_ms=None,
|
||||
expires_at_unix_ms=None,
|
||||
)
|
||||
)
|
||||
return requests
|
||||
|
||||
|
||||
class EventPipeline(EventPipelineProtocol):
|
||||
def __init__(
|
||||
self,
|
||||
filter_chain: SourceFilterChain,
|
||||
normalizer: EventNormalizer,
|
||||
classifier: EventClassifier,
|
||||
serializer: NdjsonSerializer,
|
||||
output_writer: StdoutOutputWriter,
|
||||
trigger_engine: TriggerEngine,
|
||||
command_dispatcher: CommandDispatcherProtocol,
|
||||
observability: Observability | None = None,
|
||||
) -> None:
|
||||
self._filter_chain = filter_chain
|
||||
self._normalizer = normalizer
|
||||
self._classifier = classifier
|
||||
self._serializer = serializer
|
||||
self._output_writer = output_writer
|
||||
self._trigger_engine = trigger_engine
|
||||
self._command_dispatcher = command_dispatcher
|
||||
self._observability = observability
|
||||
self._command_tasks: set[asyncio.Task[None]] = set()
|
||||
|
||||
async def ingest(self, event: RawSourceEvent) -> list[CommandResult]:
|
||||
return await self.process(event)
|
||||
|
||||
async def process(self, raw_event: RawSourceEvent) -> list[CommandResult]:
|
||||
if not self._filter_chain.apply(raw_event, raw_event.source_type):
|
||||
return []
|
||||
|
||||
normalized = self._normalizer.normalize(raw_event)
|
||||
if self._observability is not None:
|
||||
self._observability.record_event(normalized.event_kind)
|
||||
|
||||
disposition = self._classifier.classify(normalized)
|
||||
if disposition.action != "drop":
|
||||
line = self._serializer.serialize(normalized)
|
||||
self._output_writer.write_line(line)
|
||||
|
||||
results: list[CommandResult] = []
|
||||
if disposition.action == "serialize_and_trigger":
|
||||
for request in self._trigger_engine.evaluate(normalized, disposition):
|
||||
self._schedule_command_dispatch(request)
|
||||
return results
|
||||
|
||||
def _schedule_command_dispatch(self, request: CommandRequest) -> None:
|
||||
task = asyncio.create_task(self._dispatch_command(request))
|
||||
self._command_tasks.add(task)
|
||||
task.add_done_callback(self._command_tasks.discard)
|
||||
|
||||
async def _dispatch_command(self, request: CommandRequest) -> None:
|
||||
try:
|
||||
result = await self._command_dispatcher.dispatch(request)
|
||||
if self._observability is not None:
|
||||
self._observability.record_command_result(
|
||||
result.execution.execution_status
|
||||
)
|
||||
except Exception:
|
||||
if self._observability is not None:
|
||||
self._observability.log_exception("command dispatch failed")
|
||||
|
||||
async def close(self) -> None:
|
||||
if not self._command_tasks:
|
||||
return
|
||||
await asyncio.gather(*tuple(self._command_tasks), return_exceptions=True)
|
||||
|
||||
|
||||
class ApplicationRuntime:
|
||||
def __init__(
|
||||
self,
|
||||
sources: list[EventSourceProtocol],
|
||||
pipeline: EventPipelineProtocol,
|
||||
lifecycle_service: LifecycleServiceProtocol,
|
||||
observability: Observability | None = None,
|
||||
) -> None:
|
||||
self._sources = list(sources)
|
||||
self._pipeline = pipeline
|
||||
self._lifecycle_service = lifecycle_service
|
||||
self._observability = observability
|
||||
self._stop_event = asyncio.Event()
|
||||
self._pump_tasks: list[asyncio.Task[None]] = []
|
||||
|
||||
async def run(self) -> None:
|
||||
await self._start_sources()
|
||||
try:
|
||||
await self._lifecycle_service.start()
|
||||
self._pump_tasks = [
|
||||
asyncio.create_task(self._pump_source(source))
|
||||
for source in self._sources
|
||||
]
|
||||
await self._stop_event.wait()
|
||||
finally:
|
||||
await self._shutdown()
|
||||
|
||||
async def _start_sources(self) -> None:
|
||||
for source in self._sources:
|
||||
await source.start()
|
||||
|
||||
async def _shutdown(self) -> None:
|
||||
try:
|
||||
close = getattr(self._pipeline, "close", None)
|
||||
if callable(close):
|
||||
await close()
|
||||
finally:
|
||||
await self._lifecycle_service.stop()
|
||||
for task in self._pump_tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*self._pump_tasks, return_exceptions=True)
|
||||
for source in self._sources:
|
||||
await source.stop()
|
||||
|
||||
async def _pump_source(self, source: EventSourceProtocol) -> None:
|
||||
try:
|
||||
while not self._stop_event.is_set():
|
||||
event = await source.read_event()
|
||||
if event is None:
|
||||
break
|
||||
await self.handle_event(event)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
if self._observability is not None:
|
||||
self._observability.log_exception("source worker failed")
|
||||
self._stop_event.set()
|
||||
else:
|
||||
self._stop_event.set()
|
||||
|
||||
async def handle_event(self, event: RawSourceEvent) -> None:
|
||||
if event.source_type == "runtime" and isinstance(event.raw_payload, Mapping):
|
||||
if event.raw_payload.get("event_kind") == "stop":
|
||||
self._stop_event.set()
|
||||
await self._pipeline.process(event)
|
||||
|
||||
async def handle_command_result(self, result: CommandResult) -> None:
|
||||
if self._observability is not None:
|
||||
self._observability.record_command_result(result.execution.execution_status)
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop_event.set()
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Protocol
|
||||
|
||||
from .models import CommandRequest, CommandResult, RawSourceEvent
|
||||
|
||||
|
||||
class EventSourceProtocol(Protocol):
|
||||
async def start(self) -> None: ...
|
||||
async def stop(self) -> None: ...
|
||||
async def read_event(self) -> RawSourceEvent | None: ...
|
||||
|
||||
|
||||
class LifecycleServiceProtocol(Protocol):
|
||||
async def start(self) -> None: ...
|
||||
async def stop(self) -> None: ...
|
||||
|
||||
|
||||
class CommandDispatcherProtocol(Protocol):
|
||||
async def dispatch(self, request: CommandRequest) -> CommandResult: ...
|
||||
|
||||
|
||||
class CtrlIfaceCommandClientProtocol(Protocol):
|
||||
_connected: bool
|
||||
|
||||
async def connect(self) -> None: ...
|
||||
async def execute_command(self, command: str, parse_kv: bool = False) -> CommandResult: ...
|
||||
|
||||
|
||||
class DbusCommandClientProtocol(Protocol):
|
||||
_connected: bool
|
||||
|
||||
async def connect(self) -> None: ...
|
||||
async def call_endpoint(self, command_id: str, endpoint: Any, arguments: dict[str, Any]) -> CommandResult: ...
|
||||
|
||||
|
||||
class EventPipelineProtocol(Protocol):
|
||||
async def process(self, raw_event: RawSourceEvent) -> list[CommandResult]: ...
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class Clock:
|
||||
def now_unix_ms(self) -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
||||
|
||||
class CorrelationIdProvider:
|
||||
def new_id(self, prefix: str = "c") -> str:
|
||||
return f"{prefix}-{uuid4().hex}"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Observability:
|
||||
emit_internal_metrics: bool
|
||||
log_level: str = "info"
|
||||
logger: logging.Logger | None = None
|
||||
metrics: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
def _log(self) -> logging.Logger:
|
||||
if self.logger is None:
|
||||
self.logger = logging.getLogger("rb_wf_ag")
|
||||
return self.logger
|
||||
|
||||
def increment(self, metric_name: str, amount: int = 1) -> None:
|
||||
if not self.emit_internal_metrics:
|
||||
return
|
||||
self.metrics[metric_name] = self.metrics.get(metric_name, 0) + amount
|
||||
|
||||
def record_event(self, event_kind: str) -> None:
|
||||
self.increment(f"event.{event_kind}")
|
||||
|
||||
def record_command_result(self, status: str) -> None:
|
||||
self.increment(f"command.{status}")
|
||||
|
||||
def log_info(self, message: str, *args: object) -> None:
|
||||
self._log().info(message, *args)
|
||||
|
||||
def log_warning(self, message: str, *args: object) -> None:
|
||||
self._log().warning(message, *args)
|
||||
|
||||
def log_exception(self, message: str, *args: object) -> None:
|
||||
self._log().exception(message, *args)
|
||||
|
|
@ -0,0 +1,378 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from abc import ABC, abstractmethod
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
from tempfile import gettempdir
|
||||
from typing import Any
|
||||
|
||||
from dbus_next.constants import BusType
|
||||
from dbus_next.constants import MessageType
|
||||
from dbus_next.message import Message
|
||||
from dbus_next.aio.message_bus import MessageBus
|
||||
|
||||
from .config import CtrlIfaceSourceConfig, DbusSourceConfig, RuntimeConfig
|
||||
from .models import RawSourceEvent, new_event_id
|
||||
from .pipeline import _event_kind_from_payload
|
||||
from .services import Clock, CorrelationIdProvider
|
||||
|
||||
|
||||
def _snake_case(name: str | None) -> str:
|
||||
if not name:
|
||||
return "signal"
|
||||
import re
|
||||
|
||||
value = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name)
|
||||
value = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", value)
|
||||
return value.lower()
|
||||
|
||||
|
||||
class EventSource(ABC):
|
||||
@abstractmethod
|
||||
async def start(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def stop(self) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def read_event(self) -> RawSourceEvent | None:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class RuntimeEventSource(EventSource):
|
||||
def __init__(
|
||||
self,
|
||||
config: RuntimeConfig,
|
||||
source_id: str = "runtime",
|
||||
clock: Clock | None = None,
|
||||
correlation_ids: CorrelationIdProvider | None = None,
|
||||
) -> None:
|
||||
self._config = config
|
||||
self.source_id = source_id
|
||||
self._clock = clock or Clock()
|
||||
self._correlation_ids = correlation_ids or CorrelationIdProvider()
|
||||
self._queue: asyncio.Queue[RawSourceEvent | object] = asyncio.Queue()
|
||||
self._sentinel = object()
|
||||
self._running = False
|
||||
self._timer_task: asyncio.Task[None] | None = None
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._running:
|
||||
return
|
||||
self._running = True
|
||||
if self._config.generate_timer_tick and self._config.timer_tick_interval_ms > 0:
|
||||
self._timer_task = asyncio.create_task(self._emit_timer_ticks())
|
||||
|
||||
async def stop(self) -> None:
|
||||
if not self._running and self._timer_task is None:
|
||||
return
|
||||
self._running = False
|
||||
if self._timer_task is not None:
|
||||
self._timer_task.cancel()
|
||||
await asyncio.gather(self._timer_task, return_exceptions=True)
|
||||
self._timer_task = None
|
||||
await self._queue.put(self._sentinel)
|
||||
|
||||
async def read_event(self) -> RawSourceEvent | None:
|
||||
item = await self._queue.get()
|
||||
if item is self._sentinel:
|
||||
return None
|
||||
return item # type: ignore[return-value]
|
||||
|
||||
async def emit_start(self) -> RawSourceEvent:
|
||||
return await self._emit("start")
|
||||
|
||||
async def emit_reload(self) -> RawSourceEvent:
|
||||
return await self._emit("reload")
|
||||
|
||||
async def emit_stop(self) -> RawSourceEvent:
|
||||
return await self._emit("stop")
|
||||
|
||||
async def emit_timer_tick(self) -> RawSourceEvent:
|
||||
return await self._emit("timer_tick")
|
||||
|
||||
async def _emit(self, kind: str) -> RawSourceEvent:
|
||||
event = RawSourceEvent(
|
||||
event_id=new_event_id("rt"),
|
||||
source_type="runtime",
|
||||
source_id=self.source_id,
|
||||
observed_at_unix_ms=self._clock.now_unix_ms(),
|
||||
raw_payload={
|
||||
"event_kind": kind,
|
||||
"runtime_event": kind,
|
||||
"correlation_id": self._correlation_ids.new_id("rt"),
|
||||
},
|
||||
)
|
||||
await self._queue.put(event)
|
||||
return event
|
||||
|
||||
async def _emit_timer_ticks(self) -> None:
|
||||
interval_seconds = self._config.timer_tick_interval_ms / 1000.0
|
||||
try:
|
||||
while self._running:
|
||||
await asyncio.sleep(interval_seconds)
|
||||
if self._running:
|
||||
await self.emit_timer_tick()
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
|
||||
|
||||
class CtrlIfaceEventSource(EventSource):
|
||||
def __init__(
|
||||
self,
|
||||
config: CtrlIfaceSourceConfig,
|
||||
clock: Clock | None = None,
|
||||
correlation_ids: CorrelationIdProvider | None = None,
|
||||
source_id: str = "ctrl_iface.wpa",
|
||||
) -> None:
|
||||
self._config = config
|
||||
self._clock = clock or Clock()
|
||||
self._correlation_ids = correlation_ids or CorrelationIdProvider()
|
||||
self._source_id = source_id
|
||||
self._socket: socket.socket | None = None
|
||||
self._local_path: str | None = None
|
||||
self._connected = False
|
||||
|
||||
async def connect(self) -> None:
|
||||
if self._connected:
|
||||
return
|
||||
socket_path = Path(self._config.socket_path)
|
||||
if not socket_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"ctrl_iface socket path does not exist: {socket_path}"
|
||||
)
|
||||
if not socket_path.is_socket():
|
||||
raise FileNotFoundError(
|
||||
f"ctrl_iface socket path is not a Unix socket: {socket_path}"
|
||||
)
|
||||
ctrl_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
local_path = f"{gettempdir()}/wpa_ctrl_{os.getpid()}-{id(self)}"
|
||||
try:
|
||||
Path(local_path).unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
ctrl_socket.bind(local_path)
|
||||
ctrl_socket.connect(str(socket_path))
|
||||
self._socket = ctrl_socket
|
||||
self._local_path = local_path
|
||||
self._connected = True
|
||||
|
||||
async def start(self) -> None:
|
||||
await self.connect()
|
||||
if self._config.attach_for_events:
|
||||
await self.attach()
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._connected and self._config.attach_for_events:
|
||||
try:
|
||||
await self.detach()
|
||||
except Exception:
|
||||
pass
|
||||
if self._socket is not None:
|
||||
self._socket.close()
|
||||
if self._local_path is not None:
|
||||
try:
|
||||
Path(self._local_path).unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
self._socket = None
|
||||
self._local_path = None
|
||||
self._connected = False
|
||||
|
||||
async def attach(self) -> None:
|
||||
response = await self._send_command("ATTACH")
|
||||
if response != "OK":
|
||||
raise RuntimeError(
|
||||
f"ctrl_iface ATTACH failed: {response or 'no response'}"
|
||||
)
|
||||
|
||||
async def detach(self) -> None:
|
||||
response = await self._send_command("DETACH")
|
||||
if response != "OK":
|
||||
raise RuntimeError(
|
||||
f"ctrl_iface DETACH failed: {response or 'no response'}"
|
||||
)
|
||||
|
||||
async def read_event(self) -> RawSourceEvent | None:
|
||||
if self._socket is None:
|
||||
await self.connect()
|
||||
assert self._socket is not None
|
||||
while True:
|
||||
line = await asyncio.to_thread(self._socket.recv, 4096)
|
||||
if not line:
|
||||
return None
|
||||
for text in line.decode("utf-8", errors="replace").splitlines():
|
||||
text = text.strip()
|
||||
if not text:
|
||||
continue
|
||||
if text in {"OK", "FAIL"} or text.startswith("UNKNOWN COMMAND"):
|
||||
continue
|
||||
event_kind = _event_kind_from_payload("ctrl_iface", {"line": text})
|
||||
return RawSourceEvent(
|
||||
event_id=new_event_id("ctrl"),
|
||||
source_type="ctrl_iface",
|
||||
source_id=self._source_id,
|
||||
observed_at_unix_ms=self._clock.now_unix_ms(),
|
||||
raw_payload={
|
||||
"event_kind": event_kind,
|
||||
"line": text,
|
||||
"message": text,
|
||||
"correlation_id": self._correlation_ids.new_id("ctrl"),
|
||||
},
|
||||
)
|
||||
|
||||
async def _send_command(self, command: str) -> str:
|
||||
if self._socket is None:
|
||||
await self.connect()
|
||||
assert self._socket is not None
|
||||
await asyncio.to_thread(self._socket.send, f"{command}\n".encode("utf-8"))
|
||||
line = await asyncio.to_thread(self._socket.recv, 4096)
|
||||
if not line:
|
||||
return ""
|
||||
return line.decode("utf-8", errors="replace").strip()
|
||||
|
||||
def set_socket_for_testing(self, socket_obj: Any) -> None:
|
||||
"""Install a prebuilt socket object for tests."""
|
||||
self._socket = socket_obj
|
||||
self._connected = True
|
||||
|
||||
|
||||
class DbusEventSource(EventSource):
|
||||
def __init__(
|
||||
self,
|
||||
config: DbusSourceConfig,
|
||||
clock: Clock | None = None,
|
||||
correlation_ids: CorrelationIdProvider | None = None,
|
||||
) -> None:
|
||||
self._config = config
|
||||
self._clock = clock or Clock()
|
||||
self._correlation_ids = correlation_ids or CorrelationIdProvider()
|
||||
self._bus: MessageBus | None = None
|
||||
self._queue: asyncio.Queue[RawSourceEvent | object] = asyncio.Queue()
|
||||
self._sentinel = object()
|
||||
self._connected = False
|
||||
self._root_proxy = None
|
||||
self._interface_proxy_cache: dict[str, Any] = {}
|
||||
self._signal_subscriptions: list[tuple[Any, str, Any]] = []
|
||||
|
||||
async def connect(self) -> None:
|
||||
if self._connected:
|
||||
return
|
||||
self._bus = MessageBus(bus_type=BusType.SYSTEM)
|
||||
await self._bus.connect()
|
||||
self._bus.add_message_handler(self._handle_message)
|
||||
self._connected = True
|
||||
|
||||
async def start(self) -> None:
|
||||
await self.connect()
|
||||
|
||||
async def stop(self) -> None:
|
||||
await self.unsubscribe_signals()
|
||||
if self._bus is not None:
|
||||
try:
|
||||
self._bus.remove_message_handler(self._handle_message)
|
||||
except Exception:
|
||||
pass
|
||||
self._bus.disconnect()
|
||||
self._connected = False
|
||||
await self._queue.put(self._sentinel)
|
||||
|
||||
async def read_event(self) -> RawSourceEvent | None:
|
||||
item = await self._queue.get()
|
||||
if item is self._sentinel:
|
||||
return None
|
||||
return item # type: ignore[return-value]
|
||||
|
||||
def _handle_message(self, message: Message) -> None:
|
||||
if message.message_type != MessageType.SIGNAL:
|
||||
return
|
||||
if message.interface not in {self._config.service, self._config.interface_name}:
|
||||
return
|
||||
payload = {
|
||||
"interface": message.interface,
|
||||
"path": message.path,
|
||||
"member": message.member,
|
||||
"body": message.body,
|
||||
"event_kind": _snake_case(message.member),
|
||||
"correlation_id": self._correlation_ids.new_id("dbus"),
|
||||
}
|
||||
self._queue.put_nowait(
|
||||
RawSourceEvent(
|
||||
event_id=new_event_id("dbus"),
|
||||
source_type="dbus",
|
||||
source_id=self._config.service,
|
||||
observed_at_unix_ms=self._clock.now_unix_ms(),
|
||||
raw_payload=payload,
|
||||
)
|
||||
)
|
||||
|
||||
async def resolve_root_proxy(self) -> Any:
|
||||
if self._bus is None:
|
||||
await self.connect()
|
||||
if self._root_proxy is None:
|
||||
assert self._bus is not None
|
||||
introspection = await self._bus.introspect(
|
||||
self._config.service, self._config.root_path
|
||||
)
|
||||
self._root_proxy = self._bus.get_proxy_object(
|
||||
self._config.service, self._config.root_path, introspection
|
||||
)
|
||||
return self._root_proxy
|
||||
|
||||
async def resolve_interface_proxy(self, ifname: str) -> Any:
|
||||
cached = self._interface_proxy_cache.get(ifname)
|
||||
if cached is not None:
|
||||
return cached
|
||||
root_proxy = await self.resolve_root_proxy()
|
||||
root_iface = root_proxy.get_interface(self._config.service)
|
||||
interface_path = await getattr(root_iface, "GetInterface")(ifname)
|
||||
assert self._bus is not None
|
||||
introspection = await self._bus.introspect(self._config.service, interface_path)
|
||||
proxy = self._bus.get_proxy_object(
|
||||
self._config.service, interface_path, introspection
|
||||
)
|
||||
self._interface_proxy_cache[ifname] = proxy
|
||||
return proxy
|
||||
|
||||
async def subscribe_signals(self) -> list[str]:
|
||||
root_proxy = await self.resolve_root_proxy()
|
||||
main_iface = root_proxy.get_interface(self._config.service)
|
||||
|
||||
subscriptions: list[str] = []
|
||||
|
||||
def _maybe_subscribe(signal_name: str, handler: Any) -> None:
|
||||
callback_name = f"on_{_snake_case(signal_name)}"
|
||||
callback = getattr(main_iface, callback_name, None)
|
||||
if callable(callback):
|
||||
callback(handler)
|
||||
subscriptions.append(signal_name)
|
||||
self._signal_subscriptions.append((main_iface, callback_name, handler))
|
||||
|
||||
def _on_interface_added(_interface: Any, _properties: Any) -> None:
|
||||
return None
|
||||
|
||||
def _on_interface_removed(_interface: Any) -> None:
|
||||
return None
|
||||
|
||||
def _on_properties_changed(_properties: Any) -> None:
|
||||
return None
|
||||
|
||||
_maybe_subscribe("InterfaceAdded", _on_interface_added)
|
||||
_maybe_subscribe("InterfaceRemoved", _on_interface_removed)
|
||||
_maybe_subscribe("PropertiesChanged", _on_properties_changed)
|
||||
|
||||
return subscriptions
|
||||
|
||||
async def unsubscribe_signals(self) -> None:
|
||||
while self._signal_subscriptions:
|
||||
interface, callback_name, handler = self._signal_subscriptions.pop()
|
||||
callback = getattr(interface, f"off_{callback_name[3:]}", None)
|
||||
if callable(callback):
|
||||
try:
|
||||
callback(handler)
|
||||
except Exception:
|
||||
pass
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
if str(SRC) not in sys.path:
|
||||
sys.path.insert(0, str(SRC))
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
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
|
||||
|
||||
|
||||
def test_build_application_creates_runtime(tmp_path: Path) -> None:
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(
|
||||
dedent("""
|
||||
version: 1
|
||||
runtime:
|
||||
generate_events:
|
||||
start: true
|
||||
reload: true
|
||||
stop: true
|
||||
timer_tick: false
|
||||
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: false
|
||||
socket_path: /var/run/wpa_supplicant/wlan0
|
||||
attach_for_events: true
|
||||
filters: []
|
||||
runtime:
|
||||
enabled: true
|
||||
filters: []
|
||||
classifier: {rules: []}
|
||||
triggers: {rules: []}
|
||||
commands:
|
||||
dispatch:
|
||||
strategy: explicit_destination_only
|
||||
dbus:
|
||||
enabled: false
|
||||
methods: {}
|
||||
ctrl_iface:
|
||||
enabled: false
|
||||
commands: {}
|
||||
output: {format: ndjson, target: stdout, flush_every_event: true}
|
||||
observability: {emit_internal_metrics: false, log_level: info}
|
||||
guards: {trigger_loop_guard: {}}
|
||||
"""),
|
||||
encoding="utf-8",
|
||||
)
|
||||
config = load_app_config(path)
|
||||
app = build_application(config)
|
||||
assert isinstance(app, ApplicationRuntime)
|
||||
|
||||
|
||||
def test_main_reports_startup_oserror(tmp_path: Path, monkeypatch, capsys) -> None:
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(
|
||||
dedent("""
|
||||
version: 1
|
||||
runtime:
|
||||
generate_events:
|
||||
start: true
|
||||
reload: false
|
||||
stop: false
|
||||
timer_tick: false
|
||||
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: /tmp/does-not-exist.sock
|
||||
attach_for_events: true
|
||||
filters: []
|
||||
runtime:
|
||||
enabled: true
|
||||
filters: []
|
||||
classifier: {rules: []}
|
||||
triggers: {rules: []}
|
||||
commands:
|
||||
dispatch:
|
||||
strategy: explicit_destination_only
|
||||
dbus:
|
||||
enabled: false
|
||||
methods: {}
|
||||
ctrl_iface:
|
||||
enabled: true
|
||||
commands: {}
|
||||
output: {format: ndjson, target: stdout, flush_every_event: true}
|
||||
observability: {emit_internal_metrics: false, log_level: info}
|
||||
guards: {trigger_loop_guard: {}}
|
||||
"""),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
class FakeRuntime:
|
||||
async def run(self) -> None:
|
||||
raise FileNotFoundError(
|
||||
"ctrl_iface socket path does not exist: /tmp/does-not-exist.sock"
|
||||
)
|
||||
|
||||
monkeypatch.setattr(cli, "build_application", lambda _config: FakeRuntime())
|
||||
exit_code = cli.main(["--config", str(path)])
|
||||
assert exit_code == 1
|
||||
assert "startup failed" in capsys.readouterr().err
|
||||
|
|
@ -0,0 +1,210 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from rb_wf_ag.commands import CommandDispatcher
|
||||
from rb_wf_ag.commands import CtrlIfaceCommandClient
|
||||
from rb_wf_ag.config import load_app_config
|
||||
from rb_wf_ag.models import (
|
||||
CommandExecutionResult,
|
||||
CommandRequest,
|
||||
CommandResult,
|
||||
CommandReturnedData,
|
||||
)
|
||||
from rb_wf_ag.sources import CtrlIfaceEventSource
|
||||
|
||||
|
||||
class FakeCtrlIfaceClient:
|
||||
def __init__(self) -> None:
|
||||
self._connected = False
|
||||
self.calls: list[tuple[str, bool]] = []
|
||||
|
||||
async def connect(self) -> None:
|
||||
self._connected = True
|
||||
|
||||
async def execute_command(self, command: str, parse_kv: bool = False) -> CommandResult:
|
||||
self.calls.append((command, parse_kv))
|
||||
return CommandResult(
|
||||
command_id="",
|
||||
destination="ctrl_iface",
|
||||
execution=CommandExecutionResult("succeeded"),
|
||||
returned_data=CommandReturnedData("kv", {"state": "completed"}),
|
||||
)
|
||||
|
||||
|
||||
class FakeDbusClient:
|
||||
def __init__(self) -> None:
|
||||
self._connected = False
|
||||
self.calls: list[tuple[str, str]] = []
|
||||
|
||||
async def connect(self) -> None:
|
||||
self._connected = True
|
||||
|
||||
async def call_endpoint(self, command_id: str, endpoint, arguments):
|
||||
self.calls.append((endpoint.method, command_id))
|
||||
return CommandResult(
|
||||
command_id=command_id,
|
||||
destination="dbus",
|
||||
execution=CommandExecutionResult("succeeded"),
|
||||
returned_data=CommandReturnedData(
|
||||
"structured", {"ok": True, "arguments": dict(arguments)}
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class FakeCtrlSocket:
|
||||
def __init__(self, responses: list[bytes]) -> None:
|
||||
self.responses = list(responses)
|
||||
self.sent: list[bytes] = []
|
||||
|
||||
def send(self, data: bytes) -> int:
|
||||
self.sent.append(data)
|
||||
return len(data)
|
||||
|
||||
def recv(self, _bufsize: int) -> bytes:
|
||||
if self.responses:
|
||||
return self.responses.pop(0)
|
||||
return b""
|
||||
|
||||
def close(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def _config():
|
||||
return load_app_config("""
|
||||
version: 1
|
||||
runtime:
|
||||
generate_events:
|
||||
start: true
|
||||
reload: true
|
||||
stop: true
|
||||
timer_tick: true
|
||||
timers:
|
||||
timer_tick_interval_ms: 100
|
||||
sources:
|
||||
dbus:
|
||||
enabled: true
|
||||
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: []}
|
||||
triggers: {rules: []}
|
||||
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: false, log_level: info}
|
||||
guards: {trigger_loop_guard: {}}
|
||||
""")
|
||||
|
||||
|
||||
def test_dispatcher_routes_to_explicit_destination_only() -> None:
|
||||
config = _config()
|
||||
ctrl_client = FakeCtrlIfaceClient()
|
||||
dbus_client = FakeDbusClient()
|
||||
dispatcher = CommandDispatcher(
|
||||
config, dbus_client=dbus_client, ctrl_iface_client=ctrl_client
|
||||
)
|
||||
|
||||
ctrl_result = asyncio.run(
|
||||
dispatcher.dispatch(
|
||||
CommandRequest(
|
||||
command_id="cmd-1",
|
||||
command_kind="get_status",
|
||||
destination_hint="ctrl_iface",
|
||||
arguments={},
|
||||
triggered_by_event_id="evt-1",
|
||||
correlation_id=None,
|
||||
priority=None,
|
||||
not_before_unix_ms=None,
|
||||
expires_at_unix_ms=None,
|
||||
)
|
||||
)
|
||||
)
|
||||
assert ctrl_result.execution.execution_status == "succeeded"
|
||||
assert ctrl_client.calls == [("STATUS", True)]
|
||||
|
||||
dbus_result = asyncio.run(
|
||||
dispatcher.dispatch(
|
||||
CommandRequest(
|
||||
command_id="cmd-2",
|
||||
command_kind="get_interface",
|
||||
destination_hint="dbus",
|
||||
arguments={"ifname": "wlan0"},
|
||||
triggered_by_event_id="evt-2",
|
||||
correlation_id=None,
|
||||
priority=None,
|
||||
not_before_unix_ms=None,
|
||||
expires_at_unix_ms=None,
|
||||
)
|
||||
)
|
||||
)
|
||||
assert dbus_result.execution.execution_status == "succeeded"
|
||||
assert dbus_client.calls == [("GetInterface", "cmd-2")]
|
||||
|
||||
unsupported = asyncio.run(
|
||||
dispatcher.dispatch(
|
||||
CommandRequest(
|
||||
command_id="cmd-3",
|
||||
command_kind="get_status",
|
||||
destination_hint=None,
|
||||
arguments={},
|
||||
triggered_by_event_id="evt-3",
|
||||
correlation_id=None,
|
||||
priority=None,
|
||||
not_before_unix_ms=None,
|
||||
expires_at_unix_ms=None,
|
||||
)
|
||||
)
|
||||
)
|
||||
assert unsupported.execution.execution_status == "unsupported"
|
||||
assert unsupported.destination == "unsupported"
|
||||
|
||||
|
||||
def test_ctrl_iface_status_parses_multiline_datagram_response() -> None:
|
||||
client = CtrlIfaceCommandClient("/tmp/unused.sock")
|
||||
client.set_socket_for_testing(
|
||||
FakeCtrlSocket([b"bssid=aa:bb:cc:dd:ee:ff\nssid=test-net\n", b"OK\n"])
|
||||
)
|
||||
|
||||
result = asyncio.run(client.status())
|
||||
|
||||
assert result.execution.execution_status == "succeeded"
|
||||
assert result.returned_data.data_type == "kv"
|
||||
assert result.returned_data.payload == {
|
||||
"bssid": "aa:bb:cc:dd:ee:ff",
|
||||
"ssid": "test-net",
|
||||
}
|
||||
|
||||
|
||||
def test_ctrl_iface_event_source_fails_when_attach_is_rejected() -> None:
|
||||
config = _config()
|
||||
source = CtrlIfaceEventSource(config.ctrl_iface)
|
||||
source.set_socket_for_testing(FakeCtrlSocket([b"FAIL\n"]))
|
||||
|
||||
try:
|
||||
asyncio.run(source.start())
|
||||
except RuntimeError as exc:
|
||||
assert "ATTACH failed" in str(exc)
|
||||
else:
|
||||
raise AssertionError("expected ATTACH failure to raise RuntimeError")
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from textwrap import dedent
|
||||
|
||||
import pytest
|
||||
|
||||
from rb_wf_ag.config import load_app_config
|
||||
|
||||
|
||||
def _write_config(tmp_path: Path, text: str) -> Path:
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(text, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def test_load_app_config(tmp_path: Path) -> None:
|
||||
path = _write_config(
|
||||
tmp_path,
|
||||
dedent("""
|
||||
version: 1
|
||||
runtime:
|
||||
generate_events:
|
||||
start: true
|
||||
reload: true
|
||||
stop: true
|
||||
timer_tick: true
|
||||
timers:
|
||||
timer_tick_interval_ms: 100
|
||||
sources:
|
||||
dbus:
|
||||
enabled: true
|
||||
bus: system
|
||||
service: fi.w1.wpa_supplicant1
|
||||
root_path: /fi/w1/wpa_supplicant1
|
||||
interface_name: fi.w1.wpa_supplicant1.Interface
|
||||
filters:
|
||||
- id: dbus-keep
|
||||
enabled: true
|
||||
match:
|
||||
event_kind_in: [interface_added, properties_changed]
|
||||
action: keep
|
||||
ctrl_iface:
|
||||
enabled: true
|
||||
socket_path: /var/run/wpa_supplicant/wlan0
|
||||
attach_for_events: true
|
||||
filters:
|
||||
- id: ctrl-keep
|
||||
enabled: true
|
||||
match:
|
||||
event_kind_in: [CTRL-EVENT-SCAN-RESULTS]
|
||||
action: keep
|
||||
runtime:
|
||||
enabled: true
|
||||
filters:
|
||||
- id: runtime-keep
|
||||
enabled: true
|
||||
match:
|
||||
event_kind_in: [start, reload, stop, timer_tick]
|
||||
action: keep
|
||||
classifier:
|
||||
rules:
|
||||
- id: serialize-start
|
||||
enabled: true
|
||||
match:
|
||||
source_type: runtime
|
||||
event_kind: start
|
||||
disposition: serialize_only
|
||||
triggers:
|
||||
rules:
|
||||
- id: on-start
|
||||
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
|
||||
"""),
|
||||
)
|
||||
|
||||
config = load_app_config(path)
|
||||
assert config.version == 1
|
||||
assert config.runtime.timer_tick_interval_ms == 100
|
||||
assert config.dbus.service == "fi.w1.wpa_supplicant1"
|
||||
assert config.ctrl_iface.socket_path.endswith("wlan0")
|
||||
assert config.classifier_rules[0].disposition == "serialize_only"
|
||||
assert config.trigger_rules[0].command["command_kind"] == "get_status"
|
||||
assert config.commands.ctrl_iface.commands["get_status"] == "STATUS"
|
||||
|
||||
|
||||
def test_load_app_config_rejects_bad_version(tmp_path: Path) -> None:
|
||||
path = _write_config(
|
||||
tmp_path,
|
||||
dedent("""
|
||||
version: 2
|
||||
runtime: {}
|
||||
sources:
|
||||
dbus:
|
||||
enabled: false
|
||||
bus: system
|
||||
service: fi.w1.wpa_supplicant1
|
||||
root_path: /fi/w1/wpa_supplicant1
|
||||
interface_name: fi.w1.wpa_supplicant1.Interface
|
||||
ctrl_iface:
|
||||
enabled: false
|
||||
socket_path: /var/run/wpa_supplicant/wlan0
|
||||
attach_for_events: true
|
||||
runtime:
|
||||
enabled: false
|
||||
classifier: {rules: []}
|
||||
triggers: {rules: []}
|
||||
commands:
|
||||
dispatch: {strategy: explicit_destination_only}
|
||||
dbus: {enabled: false, methods: {}}
|
||||
ctrl_iface: {enabled: false, commands: {}}
|
||||
output: {format: ndjson, target: stdout, flush_every_event: true}
|
||||
observability: {emit_internal_metrics: false, log_level: info}
|
||||
guards: {trigger_loop_guard: {}}
|
||||
"""),
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="unsupported configuration version"):
|
||||
load_app_config(path)
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
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
|
||||
|
||||
|
||||
def _ifname() -> str | None:
|
||||
value = os.environ.get("RB_WF_AG_DBUS_IFNAME") or os.environ.get("WPA_DBUS_IFNAME")
|
||||
if not value:
|
||||
return None
|
||||
value = value.strip()
|
||||
return value or None
|
||||
|
||||
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.skipif(_ifname() is None, reason="live dbus interface name not configured")
|
||||
def test_live_dbus_get_interface_smoke() -> None:
|
||||
ifname = _ifname()
|
||||
assert ifname is not None
|
||||
|
||||
async def _run() -> None:
|
||||
client = DbusCommandClient(
|
||||
service="fi.w1.wpa_supplicant1",
|
||||
root_path="/fi/w1/wpa_supplicant1",
|
||||
interface_name="fi.w1.wpa_supplicant1.Interface",
|
||||
bus_type="system",
|
||||
)
|
||||
try:
|
||||
result = await client.get_interface(ifname)
|
||||
finally:
|
||||
await client.close()
|
||||
assert result.execution.execution_status == "succeeded"
|
||||
assert result.destination == "dbus"
|
||||
assert result.returned_data.data_type == "structured"
|
||||
assert result.returned_data.payload is not None
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.skipif(_ifname() is None, reason="live dbus interface name not configured")
|
||||
def test_live_dbus_signal_subscription_smoke() -> None:
|
||||
async def _run() -> None:
|
||||
config = load_app_config("""
|
||||
version: 1
|
||||
runtime:
|
||||
generate_events:
|
||||
start: false
|
||||
reload: false
|
||||
stop: false
|
||||
timer_tick: false
|
||||
timers:
|
||||
timer_tick_interval_ms: 100
|
||||
sources:
|
||||
dbus:
|
||||
enabled: true
|
||||
bus: system
|
||||
service: fi.w1.wpa_supplicant1
|
||||
root_path: /fi/w1/wpa_supplicant1
|
||||
interface_name: fi.w1.wpa_supplicant1.Interface
|
||||
filters: []
|
||||
ctrl_iface:
|
||||
enabled: false
|
||||
socket_path: /var/run/wpa_supplicant/wlan0
|
||||
attach_for_events: false
|
||||
filters: []
|
||||
runtime:
|
||||
enabled: false
|
||||
filters: []
|
||||
classifier: {rules: []}
|
||||
triggers: {rules: []}
|
||||
commands:
|
||||
dispatch:
|
||||
strategy: explicit_destination_only
|
||||
dbus:
|
||||
enabled: true
|
||||
methods: {}
|
||||
ctrl_iface:
|
||||
enabled: false
|
||||
commands: {}
|
||||
output: {format: ndjson, target: stdout, flush_every_event: true}
|
||||
observability: {emit_internal_metrics: false, log_level: info}
|
||||
guards: {trigger_loop_guard: {}}
|
||||
""")
|
||||
source = DbusEventSource(config.dbus)
|
||||
try:
|
||||
await source.start()
|
||||
subscriptions = await source.subscribe_signals()
|
||||
assert subscriptions
|
||||
assert "InterfaceAdded" in subscriptions
|
||||
assert "InterfaceRemoved" in subscriptions
|
||||
assert "PropertiesChanged" in subscriptions
|
||||
finally:
|
||||
await source.stop()
|
||||
|
||||
asyncio.run(_run())
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from rb_wf_ag.commands import CtrlIfaceCommandClient
|
||||
|
||||
|
||||
def _socket_path() -> str | None:
|
||||
candidate = os.environ.get("RB_WF_AG_CTRL_IFACE_SOCKET") or os.environ.get(
|
||||
"WPA_CTRL_IFACE_PATH"
|
||||
)
|
||||
if not candidate:
|
||||
return None
|
||||
path = Path(candidate)
|
||||
if not path.exists():
|
||||
return None
|
||||
return str(path)
|
||||
|
||||
|
||||
@pytest.mark.integration
|
||||
@pytest.mark.skipif(
|
||||
_socket_path() is None, reason="live ctrl_iface socket not configured"
|
||||
)
|
||||
def test_live_ctrl_iface_status_smoke() -> None:
|
||||
socket_path = _socket_path()
|
||||
assert socket_path is not None
|
||||
|
||||
async def _run() -> None:
|
||||
client = CtrlIfaceCommandClient(socket_path)
|
||||
try:
|
||||
result = await client.status()
|
||||
finally:
|
||||
await client.close()
|
||||
assert result.execution.execution_status == "succeeded"
|
||||
assert result.returned_data.data_type == "kv"
|
||||
payload = result.returned_data.payload
|
||||
assert isinstance(payload, dict)
|
||||
assert "state" in payload
|
||||
|
||||
import asyncio
|
||||
|
||||
asyncio.run(_run())
|
||||
|
|
@ -0,0 +1,240 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from io import StringIO
|
||||
|
||||
from rb_wf_ag.models import (
|
||||
CommandExecutionResult,
|
||||
CommandRequest,
|
||||
CommandResult,
|
||||
CommandReturnedData,
|
||||
EventClassifierRule,
|
||||
RawSourceEvent,
|
||||
SourceFilterRule,
|
||||
TriggerRule,
|
||||
)
|
||||
from rb_wf_ag.pipeline import (
|
||||
ApplicationRuntime,
|
||||
EventClassifier,
|
||||
EventNormalizer,
|
||||
EventPipeline,
|
||||
NdjsonSerializer,
|
||||
SourceFilterChain,
|
||||
StdoutOutputWriter,
|
||||
TriggerEngine,
|
||||
TriggerLoopGuard,
|
||||
)
|
||||
from rb_wf_ag.services import Clock
|
||||
|
||||
|
||||
class FixedClock(Clock):
|
||||
def __init__(self, now: int) -> None:
|
||||
self._now = now
|
||||
|
||||
def now_unix_ms(self) -> int:
|
||||
return self._now
|
||||
|
||||
|
||||
class RecordingDispatcher:
|
||||
def __init__(self) -> None:
|
||||
self.requests: list[CommandRequest] = []
|
||||
|
||||
async def dispatch(self, request: CommandRequest) -> CommandResult:
|
||||
self.requests.append(request)
|
||||
return CommandResult(
|
||||
command_id=request.command_id,
|
||||
destination=request.destination_hint or "unsupported",
|
||||
execution=CommandExecutionResult("succeeded"),
|
||||
returned_data=CommandReturnedData("none", None),
|
||||
)
|
||||
|
||||
|
||||
class FakeSource:
|
||||
def __init__(self, events: list[RawSourceEvent]) -> None:
|
||||
self._events = list(events)
|
||||
self.started = False
|
||||
self.stopped = False
|
||||
|
||||
async def start(self) -> None:
|
||||
self.started = True
|
||||
|
||||
async def stop(self) -> None:
|
||||
self.stopped = True
|
||||
|
||||
async def read_event(self) -> RawSourceEvent | None:
|
||||
if not self._events:
|
||||
return None
|
||||
return self._events.pop(0)
|
||||
|
||||
|
||||
class FakeLifecycle:
|
||||
async def start(self) -> None:
|
||||
return None
|
||||
|
||||
async def stop(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def _raw_runtime_event(kind: str = "start") -> RawSourceEvent:
|
||||
return RawSourceEvent(
|
||||
event_id="rt-1",
|
||||
source_type="runtime",
|
||||
source_id="runtime",
|
||||
observed_at_unix_ms=123,
|
||||
raw_payload={
|
||||
"event_kind": kind,
|
||||
"severity": "info",
|
||||
"payload": {"state": kind},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_filter_classifier_serializer_and_trigger_pipeline() -> None:
|
||||
clock = FixedClock(1_700_000_000_000)
|
||||
filter_chain = SourceFilterChain(
|
||||
{
|
||||
"runtime": [
|
||||
SourceFilterRule(
|
||||
rule_id="keep-start",
|
||||
enabled=True,
|
||||
match={"event_kind_in": ["start", "reload", "stop", "timer_tick"]},
|
||||
action="keep",
|
||||
)
|
||||
]
|
||||
}
|
||||
)
|
||||
classifier = EventClassifier(
|
||||
[
|
||||
EventClassifierRule(
|
||||
rule_id="serialize-start",
|
||||
enabled=True,
|
||||
match={"source_type": "runtime", "event_kind": "start"},
|
||||
disposition="serialize_and_trigger",
|
||||
)
|
||||
]
|
||||
)
|
||||
dispatcher = RecordingDispatcher()
|
||||
pipeline = EventPipeline(
|
||||
filter_chain=filter_chain,
|
||||
normalizer=EventNormalizer(clock=clock),
|
||||
classifier=classifier,
|
||||
serializer=NdjsonSerializer(),
|
||||
output_writer=StdoutOutputWriter(stream=StringIO()),
|
||||
trigger_engine=TriggerEngine(
|
||||
rules=[
|
||||
TriggerRule(
|
||||
rule_id="on-start",
|
||||
enabled=True,
|
||||
match={"source_type": "runtime", "event_kind": "start"},
|
||||
command={
|
||||
"command_kind": "get_status",
|
||||
"destination": "ctrl_iface",
|
||||
"arguments": {},
|
||||
},
|
||||
cooldown_ms=2000,
|
||||
max_retries=0,
|
||||
)
|
||||
],
|
||||
loop_guard=TriggerLoopGuard(default_cooldown_ms=5000, dedup_window_ms=3000),
|
||||
clock=clock,
|
||||
),
|
||||
command_dispatcher=dispatcher,
|
||||
)
|
||||
|
||||
stream = pipeline._output_writer._stream
|
||||
assert isinstance(stream, StringIO)
|
||||
async def _run_once() -> list[CommandResult]:
|
||||
results = await pipeline.process(_raw_runtime_event("start"))
|
||||
await asyncio.sleep(0)
|
||||
return results
|
||||
|
||||
results = asyncio.run(_run_once())
|
||||
assert len(results) == 0
|
||||
assert len(dispatcher.requests) == 1
|
||||
|
||||
stream.seek(0)
|
||||
line = stream.read().strip()
|
||||
output = json.loads(line)
|
||||
assert output["event_kind"] == "start"
|
||||
assert output["source_type"] == "runtime"
|
||||
assert output["payload"]["payload"]["state"] == "start"
|
||||
|
||||
results_again = asyncio.run(_run_once())
|
||||
assert len(results_again) == 0
|
||||
assert len(dispatcher.requests) == 1
|
||||
|
||||
|
||||
def test_filter_chain_drops_non_matching_event() -> None:
|
||||
chain = SourceFilterChain(
|
||||
{
|
||||
"ctrl_iface": [
|
||||
SourceFilterRule(
|
||||
rule_id="keep-scan-results",
|
||||
enabled=True,
|
||||
match={"event_kind_in": ["CTRL-EVENT-SCAN-RESULTS"]},
|
||||
action="keep",
|
||||
)
|
||||
]
|
||||
}
|
||||
)
|
||||
event = RawSourceEvent(
|
||||
event_id="ctrl-1",
|
||||
source_type="ctrl_iface",
|
||||
source_id="ctrl_iface.wpa",
|
||||
observed_at_unix_ms=1,
|
||||
raw_payload={
|
||||
"event_kind": "CTRL-EVENT-BSS-ADDED",
|
||||
"line": "CTRL-EVENT-BSS-ADDED",
|
||||
},
|
||||
)
|
||||
assert chain.apply(event, "ctrl_iface") is True
|
||||
|
||||
drop_chain = SourceFilterChain(
|
||||
{
|
||||
"dbus": [
|
||||
SourceFilterRule(
|
||||
rule_id="drop-debug",
|
||||
enabled=True,
|
||||
match={
|
||||
"event_kind": "properties_changed",
|
||||
"payload_has_any_key": ["DebugLevel"],
|
||||
},
|
||||
action="drop",
|
||||
)
|
||||
]
|
||||
}
|
||||
)
|
||||
dbus_event = RawSourceEvent(
|
||||
event_id="dbus-1",
|
||||
source_type="dbus",
|
||||
source_id="dbus.wpa",
|
||||
observed_at_unix_ms=1,
|
||||
raw_payload={
|
||||
"Interface": "fi.w1.wpa_supplicant1",
|
||||
"Member": "PropertiesChanged",
|
||||
"DebugLevel": "off",
|
||||
},
|
||||
)
|
||||
assert drop_chain.apply(dbus_event, "dbus") is False
|
||||
|
||||
|
||||
def test_application_runtime_processes_sources_until_eof() -> None:
|
||||
event = _raw_runtime_event("start")
|
||||
source = FakeSource([event])
|
||||
processed: list[str] = []
|
||||
|
||||
class FakePipeline:
|
||||
async def process(self, raw_event: RawSourceEvent) -> list[CommandResult]:
|
||||
processed.append(raw_event.event_id)
|
||||
return []
|
||||
|
||||
runtime = ApplicationRuntime(
|
||||
sources=[source],
|
||||
pipeline=FakePipeline(),
|
||||
lifecycle_service=FakeLifecycle(),
|
||||
)
|
||||
asyncio.run(runtime.run())
|
||||
assert processed == ["rt-1"]
|
||||
assert source.started is True
|
||||
assert source.stopped is True
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, ContextManager, NoReturn, TypeVar
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
class _Mark:
|
||||
integration: Any
|
||||
skipif: Any
|
||||
|
||||
def __getattr__(self, name: str) -> Any: ...
|
||||
|
||||
mark: _Mark
|
||||
|
||||
def skip(reason: str = ...) -> NoReturn: ...
|
||||
def raises(
|
||||
expected_exception: type[BaseException] | tuple[type[BaseException], ...],
|
||||
*args: Any,
|
||||
**kwargs: Any,
|
||||
) -> ContextManager[Any]: ...
|
||||
def fixture(*args: Any, **kwargs: Any) -> Callable[[Callable[..., T]], Callable[..., T]]: ...
|
||||
Loading…
Reference in New Issue