коррекции по замечаниям pyright

This commit is contained in:
Ilgiz Kalmetyev 2026-04-18 22:32:35 +05:00
parent 9215021be4
commit 984b5522c9
56 changed files with 674 additions and 451 deletions

5
pyrightconfig.json Normal file
View File

@ -0,0 +1,5 @@
{
"exclude": [
"src/app/shared/contracts/proto/v1"
]
}

View File

@ -1,19 +1,93 @@
"""Base adapter abstractions."""
from __future__ import annotations
from collections.abc import Iterable
from typing import Any, Protocol, runtime_checkable
from app.shared.contracts import CommandRequest, CommandResult, StatusSnapshot
from .interfaces import (
AcquisitionStrategy,
AdapterRuntime,
CommandExecutor,
ConnectionDriver,
MessageMarker,
MessageParser,
MessagePrefilter,
MessageValidator,
BaseAcquisitionStrategy,
BaseAdapterFactory,
BaseAdapterRuntime,
BaseCommandExecutor,
BaseConnectionDriver,
BaseExternalWrapper,
BaseMessageMarker,
BaseMessageParser,
BaseMessagePrefilter,
BaseMessageValidator,
)
@runtime_checkable
class ConnectionDriver(Protocol):
def connect(self) -> None: ...
def disconnect(self) -> None: ...
def is_alive(self) -> bool: ...
def receive(self) -> Any | None: ...
def send(self, message: Any) -> None: ...
@runtime_checkable
class AcquisitionStrategy(Protocol):
def acquire(self, driver: ConnectionDriver) -> Iterable[Any]: ...
@runtime_checkable
class MessageParser(Protocol):
def parse(self, message: Any) -> Any: ...
@runtime_checkable
class MessageValidator(Protocol):
def validate(self, message: Any) -> Any: ...
@runtime_checkable
class MessagePrefilter(Protocol):
def prefilter(self, message: Any) -> Any: ...
@runtime_checkable
class MessageMarker(Protocol):
def mark(self, message: Any) -> Any: ...
@runtime_checkable
class CommandExecutor(Protocol):
def execute(self, request: CommandRequest) -> CommandResult: ...
@runtime_checkable
class AdapterRuntime(Protocol):
def start(self) -> None: ...
def stop(self) -> None: ...
def run_once(self) -> int: ...
def status_snapshot(self) -> StatusSnapshot: ...
__all__ = [
"AcquisitionStrategy",
"AdapterRuntime",
"BaseAcquisitionStrategy",
"BaseAdapterFactory",
"BaseAdapterRuntime",
"BaseCommandExecutor",
"BaseConnectionDriver",
"BaseExternalWrapper",
"BaseMessageMarker",
"BaseMessageParser",
"BaseMessagePrefilter",
"BaseMessageValidator",
"CommandExecutor",
"ConnectionDriver",
"MessageMarker",

View File

@ -1,99 +1,116 @@
"""Adapter stage interfaces shared across adapter implementations."""
"""Universal base interfaces and abstract classes for the skeleton adapter."""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Iterable
from typing import Protocol, TypeVar, runtime_checkable
from app.shared.contracts import CommandRequest, CommandResult, StatusSnapshot
RawMessageT = TypeVar("RawMessageT")
ParsedMessageT = TypeVar("ParsedMessageT")
ValidatedMessageT = TypeVar("ValidatedMessageT")
PrefilteredMessageT = TypeVar("PrefilteredMessageT")
MarkedMessageT = TypeVar("MarkedMessageT")
@runtime_checkable
class ConnectionDriver(Protocol[RawMessageT]):
class BaseConnectionDriver[RawMessageT](ABC):
"""Transport boundary for a concrete connection."""
def connect(self) -> None:
"""Open the underlying connection."""
@abstractmethod
def connect(self) -> None: ...
def disconnect(self) -> None:
"""Close the underlying connection."""
@abstractmethod
def disconnect(self) -> None: ...
def is_alive(self) -> bool:
"""Return whether the connection is healthy and usable."""
@abstractmethod
def is_alive(self) -> bool: ...
def receive(self) -> RawMessageT | None:
"""Receive one raw message from the transport."""
@abstractmethod
def receive(self) -> RawMessageT | None: ...
def send(self, message: RawMessageT) -> None:
"""Send one raw message to the transport."""
@abstractmethod
def send(self, message: RawMessageT) -> None: ...
@runtime_checkable
class AcquisitionStrategy(Protocol[RawMessageT]):
class BaseAcquisitionStrategy[RawMessageT](ABC):
"""Strategy that pulls raw messages using a connection driver."""
def acquire(self, driver: ConnectionDriver[RawMessageT]) -> Iterable[RawMessageT]:
"""Acquire raw messages from the driver."""
@abstractmethod
def acquire(
self,
driver: BaseConnectionDriver[RawMessageT],
) -> Iterable[RawMessageT]: ...
@runtime_checkable
class MessageParser(Protocol[RawMessageT, ParsedMessageT]):
class BaseMessageParser[RawMessageT, ParsedMessageT](ABC):
"""Convert raw transport messages into canonical adapter messages."""
def parse(self, message: RawMessageT) -> ParsedMessageT:
"""Parse one raw message into the internal canonical form."""
@abstractmethod
def parse(self, message: RawMessageT) -> ParsedMessageT: ...
@runtime_checkable
class MessageValidator(Protocol[ValidatedMessageT]):
class BaseMessageValidator[ValidatedMessageT](ABC):
"""Validate a canonical message without mutating it."""
def validate(self, message: ValidatedMessageT) -> ValidatedMessageT:
"""Validate and return the same or a compatible message object."""
@abstractmethod
def validate(self, message: ValidatedMessageT) -> ValidatedMessageT: ...
@runtime_checkable
class MessagePrefilter(Protocol[PrefilteredMessageT]):
class BaseMessagePrefilter[PrefilteredMessageT](ABC):
"""Apply a no-op or rule-based prefilter step to a canonical message."""
def prefilter(self, message: PrefilteredMessageT) -> PrefilteredMessageT:
"""Prefilter and return the same or a compatible message object."""
@abstractmethod
def prefilter(self, message: PrefilteredMessageT) -> PrefilteredMessageT: ...
@runtime_checkable
class MessageMarker(Protocol[MarkedMessageT]):
class BaseMessageMarker[MarkedMessageT](ABC):
"""Apply message marking or enrichment without changing the pipeline shape."""
def mark(self, message: MarkedMessageT) -> MarkedMessageT:
"""Mark and return the same or a compatible message object."""
@abstractmethod
def mark(self, message: MarkedMessageT) -> MarkedMessageT: ...
@runtime_checkable
class CommandExecutor(Protocol):
class BaseCommandExecutor(ABC):
"""Execute control commands against the adapter."""
def execute(self, request: CommandRequest) -> CommandResult:
"""Execute a command and return the result."""
@abstractmethod
def execute(self, request: CommandRequest) -> CommandResult: ...
@runtime_checkable
class AdapterRuntime(Protocol):
class BaseAdapterRuntime(ABC):
"""Lifecycle and orchestration contract for an adapter runtime."""
def start(self) -> None:
"""Enter the running state."""
@abstractmethod
def start(self) -> None: ...
def stop(self) -> None:
"""Request a clean stop."""
@abstractmethod
def stop(self) -> None: ...
def run_once(self) -> int:
"""Process one acquisition cycle and return the number of messages handled."""
@abstractmethod
def run_once(self) -> int: ...
def status_snapshot(self) -> StatusSnapshot:
"""Return the current adapter status snapshot."""
@abstractmethod
def status_snapshot(self) -> StatusSnapshot: ...
class BaseAdapterFactory[ConfigT, RuntimeT](ABC):
"""Create adapter runtimes from typed configuration objects."""
@abstractmethod
def create(self, config: ConfigT) -> RuntimeT: ...
class BaseExternalWrapper[RequestT, ResponseT](ABC):
"""Boundary around vendor- or source-specific external APIs."""
@abstractmethod
def invoke(self, request: RequestT) -> ResponseT: ...
__all__ = [
"BaseAcquisitionStrategy",
"BaseAdapterFactory",
"BaseAdapterRuntime",
"BaseCommandExecutor",
"BaseConnectionDriver",
"BaseExternalWrapper",
"BaseMessageMarker",
"BaseMessageParser",
"BaseMessagePrefilter",
"BaseMessageValidator",
]

View File

@ -12,4 +12,4 @@ __all__ = [
"DBusPollingStrategy",
"DBusStreamStrategy",
"create_dbus_adapter_runtime",
]
]

View File

@ -37,8 +37,6 @@ def _matches_signal(message: RawMessage, signal_name: str | None) -> bool:
@dataclass(slots=True, frozen=True)
class DBusPollingStrategy(BaseAcquisitionStrategy[RawMessage]):
"""Poll the D-Bus connection for signal messages."""
interval_seconds: float = 1.0
initial_delay_seconds: float = 0.0
run_immediately: bool = True
@ -74,8 +72,6 @@ class DBusPollingStrategy(BaseAcquisitionStrategy[RawMessage]):
@dataclass(slots=True)
class DBusCursorLikeStrategy(BaseAcquisitionStrategy[RawMessage]):
"""Read newer D-Bus messages using a cursor or sequence progress state."""
progress_state: InMemoryCursorProgressState | InMemorySequenceProgressState
position_key: str = "sequence"
position_getter: Callable[[RawMessage], int | str | None] | None = None
@ -107,17 +103,17 @@ class DBusCursorLikeStrategy(BaseAcquisitionStrategy[RawMessage]):
return messages
def commit(self) -> None:
"""Commit the latest acquired position to the in-memory progress state."""
if self._pending_position is None:
return
if hasattr(self.progress_state, "cursor"):
cursor_value = self._pending_position
if cursor_value is not None and not isinstance(cursor_value, str):
cursor_value = str(cursor_value)
self.progress_state.advance(cursor_value)
cast(InMemoryCursorProgressState, self.progress_state).advance(cursor_value)
else:
self.progress_state.advance(self._pending_position)
cast(InMemorySequenceProgressState, self.progress_state).advance(
self._pending_position
)
self._pending_position = None
def _extract_position(self, message: RawMessage) -> int | str | None:
@ -170,8 +166,6 @@ class DBusCursorLikeStrategy(BaseAcquisitionStrategy[RawMessage]):
@dataclass(slots=True)
class DBusStreamStrategy(BaseAcquisitionStrategy[RawMessage]):
"""Drain signal messages from a connected D-Bus driver."""
signal_name: str | None = None
flag_check: Callable[[BaseConnectionDriver[RawMessage]], bool] | None = None

View File

@ -2,7 +2,6 @@
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass, field
from enum import StrEnum
from typing import Any, Protocol, runtime_checkable
@ -12,6 +11,7 @@ from app.adapters.skeleton.config import (
AcquisitionDetectionKind,
AcquisitionFetchKind,
AcquisitionProgressKind,
AcquisitionTriggerKind,
ConnectionConfig,
ConnectionType,
UniversalAdapterConfigValidationError,
@ -27,8 +27,6 @@ from . import (
class DbusAcquisitionStrategyKind(StrEnum):
"""Supported D-Bus acquisition strategy kinds."""
POLLING = "polling"
CURSOR_SEQUENCE = "cursor_sequence"
STREAM = "stream"
@ -36,16 +34,13 @@ class DbusAcquisitionStrategyKind(StrEnum):
@runtime_checkable
class DbusAcquisitionStrategyBuilderProtocol(Protocol):
"""Callable that builds a D-Bus acquisition strategy from config objects."""
def __call__(
self,
connection: ConnectionConfig,
acquisition: AcquisitionConfig,
/,
**kwargs: Any,
) -> Any:
"""Build a strategy for the given config objects."""
) -> Any: ...
def _normalize_dbus_acquisition_strategy_kind(
@ -59,15 +54,26 @@ def _normalize_dbus_acquisition_strategy_kind(
) from exc
def _resolve_dbus_config(connection: ConnectionConfig):
if connection.type is not ConnectionType.DBUS:
raise UniversalAdapterConfigValidationError(
"D-Bus adapter requires connection.type=d-bus"
)
if connection.dbus is None:
raise UniversalAdapterConfigValidationError(
"D-Bus adapter requires connection.dbus to be configured"
)
return connection.dbus
def resolve_dbus_acquisition_strategy_kind(
connection: ConnectionConfig,
acquisition: AcquisitionConfig,
) -> DbusAcquisitionStrategyKind:
"""Resolve the concrete strategy kind from D-Bus acquisition config."""
_resolve_dbus_config(connection)
if (
acquisition.fetch.kind is AcquisitionFetchKind.STREAM
or acquisition.trigger.kind.value == "event"
or acquisition.trigger.kind is AcquisitionTriggerKind.EVENT
):
return DbusAcquisitionStrategyKind.STREAM
if (
@ -78,32 +84,19 @@ def resolve_dbus_acquisition_strategy_kind(
return DbusAcquisitionStrategyKind.POLLING
def _validate_dbus_connection(connection: ConnectionConfig) -> None:
if connection.type is not ConnectionType.DBUS:
raise UniversalAdapterConfigValidationError(
"D-Bus adapter requires connection.type=d-bus"
)
if connection.dbus is None:
raise UniversalAdapterConfigValidationError(
"D-Bus adapter requires connection.dbus to be configured"
)
def _build_polling_strategy(
connection: ConnectionConfig,
acquisition: AcquisitionConfig,
/,
**kwargs: Any,
) -> DBusPollingStrategy:
_validate_dbus_connection(connection)
dbus_config = _resolve_dbus_config(connection)
interval_seconds = (
acquisition.trigger.interval_seconds
if acquisition.trigger.interval_seconds is not None
else 1.0
)
selected_signal = kwargs.get("signal_name")
if selected_signal is None:
selected_signal = connection.dbus.member
selected_signal = kwargs.get("signal_name") or dbus_config.member
builder_kwargs: dict[str, Any] = {
"interval_seconds": interval_seconds,
"initial_delay_seconds": acquisition.trigger.initial_delay_seconds,
@ -123,10 +116,7 @@ def _build_cursor_sequence_strategy(
/,
**kwargs: Any,
) -> DBusCursorLikeStrategy:
_validate_dbus_connection(connection)
selected_signal = kwargs.get("signal_name")
if selected_signal is None:
selected_signal = connection.dbus.member
dbus_config = _resolve_dbus_config(connection)
progress_state = (
InMemorySequenceProgressState()
if acquisition.detection.kind is AcquisitionDetectionKind.SEQUENCE
@ -138,7 +128,7 @@ def _build_cursor_sequence_strategy(
or acquisition.detection.sequence_field
or "sequence",
position_getter=kwargs.get("position_getter"),
signal_name=selected_signal,
signal_name=kwargs.get("signal_name") or dbus_config.member,
)
@ -148,23 +138,18 @@ def _build_stream_strategy(
/,
**kwargs: Any,
) -> DBusStreamStrategy:
_validate_dbus_connection(connection)
selected_signal = kwargs.get("signal_name")
if selected_signal is None:
selected_signal = connection.dbus.member
dbus_config = _resolve_dbus_config(connection)
return DBusStreamStrategy(
signal_name=selected_signal,
signal_name=kwargs.get("signal_name") or dbus_config.member,
flag_check=kwargs.get("flag_check"),
)
@dataclass(slots=True, frozen=True)
class DbusAcquisitionStrategyRegistry:
"""Immutable registry of D-Bus acquisition strategy builders."""
builders: Mapping[DbusAcquisitionStrategyKind, DbusAcquisitionStrategyBuilderProtocol] = (
field(default_factory=dict)
)
builders: dict[
DbusAcquisitionStrategyKind, DbusAcquisitionStrategyBuilderProtocol
] = field(default_factory=dict)
def register_builder(
self,
@ -204,8 +189,6 @@ class DbusAcquisitionStrategyRegistry:
def default_dbus_acquisition_strategy_registry() -> DbusAcquisitionStrategyRegistry:
"""Return the built-in registry for supported D-Bus acquisition strategies."""
registry = DbusAcquisitionStrategyRegistry()
registry = registry.register_builder(
DbusAcquisitionStrategyKind.POLLING,
@ -228,4 +211,4 @@ __all__ = [
"DbusAcquisitionStrategyRegistry",
"default_dbus_acquisition_strategy_registry",
"resolve_dbus_acquisition_strategy_kind",
]
]

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, cast
from app.adapters.dbus_adapter.acquisition.registry import (
DbusAcquisitionStrategyRegistry,
@ -12,15 +13,20 @@ from app.adapters.dbus_adapter.acquisition.registry import (
from app.adapters.dbus_adapter.connection import DBusConnectionDriver
from app.adapters.dbus_adapter.wrappers import DbusWrapperBackend
from app.adapters.skeleton.base import (
BaseAcquisitionStrategy,
BaseAdapterFactory,
BaseConnectionDriver,
BaseMessageMarker,
BaseMessageParser,
BaseMessagePrefilter,
BaseMessageValidator,
)
from app.adapters.skeleton.config import (
AcquisitionConfig,
ConnectionConfig,
ConnectionType,
DbusConnectionConfig,
ParsingConfig,
UniversalAdapterConfig,
UniversalAdapterConfigValidationError,
)
@ -68,8 +74,9 @@ def _resolve_dbus_config(config: ConnectionConfig) -> DbusConnectionConfig:
def _build_dbus_connection_driver(
config: ConnectionConfig,
*,
backend_factory: Callable[[DbusConnectionConfig], DbusWrapperBackend | None]
| None = None,
backend_factory: (
Callable[[DbusConnectionConfig], DbusWrapperBackend | None] | None
) = None,
) -> DBusConnectionDriver:
dbus_config = _resolve_dbus_config(config)
backend = backend_factory(dbus_config) if backend_factory is not None else None
@ -99,20 +106,45 @@ class DBusAdapterFactory(
def create(self, config: UniversalAdapterConfig) -> UniversalAdapterRuntime:
_resolve_dbus_config(config.connection)
acquisition_registry = self.acquisition_registry
def connection_factory(
connection_config: ConnectionConfig, /, **kwargs: Any
) -> BaseConnectionDriver[Any]:
return cast(
BaseConnectionDriver[Any],
_build_dbus_connection_driver(
connection_config,
backend_factory=self.backend_factory,
),
)
def acquisition_factory(
connection_config: ConnectionConfig,
acquisition_config: AcquisitionConfig,
/,
**kwargs: Any,
) -> BaseAcquisitionStrategy[Any]:
strategy = acquisition_registry.build(
connection_config,
acquisition_config,
sleeper=self.sleeper,
**kwargs,
)
return cast(BaseAcquisitionStrategy[Any], strategy)
def parser_factory(
parsing_config: ParsingConfig,
/,
**kwargs: Any,
) -> BaseMessageParser[Any, CanonicalMessage]:
parser = create_message_parser(parsing_config)
return cast(BaseMessageParser[Any, CanonicalMessage], parser)
return create_universal_adapter_runtime(
config,
connection_factory=lambda connection_config: _build_dbus_connection_driver(
connection_config,
backend_factory=self.backend_factory,
),
acquisition_factory=lambda connection_config, acquisition_config: (
acquisition_registry.build(
connection_config,
acquisition_config,
sleeper=self.sleeper,
)
),
parser_factory=lambda parsing_config: create_message_parser(parsing_config),
connection_factory=connection_factory,
acquisition_factory=acquisition_factory,
parser_factory=parser_factory,
export_port=self.export_port,
observability=self.observability,
validation=self.validation,
@ -133,8 +165,9 @@ def create_dbus_adapter_runtime(
prefilter: BaseMessagePrefilter[CanonicalMessage] | None = None,
marking: BaseMessageMarker[CanonicalMessage] | None = None,
reconnect_policy: ReconnectPolicy | None = None,
backend_factory: Callable[[DbusConnectionConfig], DbusWrapperBackend | None]
| None = None,
backend_factory: (
Callable[[DbusConnectionConfig], DbusWrapperBackend | None] | None
) = None,
sleeper: Callable[[float], None] = _noop_sleep,
) -> UniversalAdapterRuntime:
"""Build a D-Bus adapter runtime directly from injected composition pieces."""
@ -145,9 +178,9 @@ def create_dbus_adapter_runtime(
validation=validation,
prefilter=prefilter,
marking=marking,
reconnect_policy=ReconnectPolicy()
if reconnect_policy is None
else reconnect_policy,
reconnect_policy=(
ReconnectPolicy() if reconnect_policy is None else reconnect_policy
),
backend_factory=backend_factory,
sleeper=sleeper,
)
@ -157,4 +190,4 @@ def create_dbus_adapter_runtime(
__all__ = [
"DBusAdapterFactory",
"create_dbus_adapter_runtime",
]
]

View File

@ -52,4 +52,4 @@ __all__ = [
"DbusWrapperError",
"DbusWrapperStateError",
"DbusWrapperTransportError",
]
]

View File

@ -31,14 +31,11 @@ class DbusWrapperTransportError(DbusWrapperError):
class DbusWrapperBackend(Protocol):
"""Backend contract used by the D-Bus wrappers."""
def connect(self, bus_name: str, timeout_seconds: float | None = None) -> None:
"""Open the bus connection."""
def connect(self, bus_name: str, timeout_seconds: float | None = None) -> None: ...
def disconnect(self) -> None:
"""Close the bus connection."""
def disconnect(self) -> None: ...
def is_alive(self) -> bool:
"""Return whether the backend is connected."""
def is_alive(self) -> bool: ...
def open_object(
self,
@ -46,8 +43,7 @@ class DbusWrapperBackend(Protocol):
object_path: str,
interface: str,
timeout_seconds: float | None = None,
) -> Any:
"""Open a proxy object or equivalent handle."""
) -> Any: ...
def call_method(
self,
@ -56,10 +52,9 @@ class DbusWrapperBackend(Protocol):
interface: str,
member: str,
arguments: tuple[Any, ...],
keyword_arguments: Mapping[str, Any],
keyword_arguments: dict[str, Any],
timeout_seconds: float | None = None,
) -> Any:
"""Invoke a D-Bus method."""
) -> Any: ...
def receive_signal(
self,
@ -68,8 +63,7 @@ class DbusWrapperBackend(Protocol):
interface: str,
member: str | None = None,
timeout_seconds: float | None = None,
) -> Any | None:
"""Receive a D-Bus signal payload."""
) -> Any | None: ...
def read_property(
self,
@ -78,17 +72,13 @@ class DbusWrapperBackend(Protocol):
interface: str,
property_name: str,
timeout_seconds: float | None = None,
) -> Any:
"""Read a D-Bus property value."""
) -> Any: ...
def health_snapshot(self, bus_name: str) -> Mapping[str, Any]:
"""Return backend health metadata."""
def health_snapshot(self, bus_name: str) -> Mapping[str, Any]: ...
@dataclass(slots=True, frozen=True)
class DbusBusConnectionRequest:
"""Request to connect to a D-Bus bus."""
bus_name: str
timeout_seconds: float | None = None
context: WrapperCallContext | None = None
@ -96,8 +86,6 @@ class DbusBusConnectionRequest:
@dataclass(slots=True, frozen=True)
class DbusBusConnectionResult:
"""Result of opening a D-Bus bus connection."""
bus_name: str
connected: bool
connected_at: datetime | None = None
@ -109,8 +97,6 @@ class DbusBusConnectionResult:
@dataclass(slots=True, frozen=True)
class DbusObjectAccessRequest:
"""Request to open a proxy object or interface handle."""
bus_name: str
object_path: str
interface: str
@ -120,8 +106,6 @@ class DbusObjectAccessRequest:
@dataclass(slots=True, frozen=True)
class DbusObjectAccessResult:
"""Result returned by the object access wrapper."""
bus_name: str
object_path: str
interface: str
@ -135,8 +119,6 @@ class DbusObjectAccessResult:
@dataclass(slots=True, frozen=True)
class DbusMethodCallRequest:
"""Request to invoke a D-Bus method."""
bus_name: str
object_path: str
interface: str
@ -149,8 +131,6 @@ class DbusMethodCallRequest:
@dataclass(slots=True, frozen=True)
class DbusMethodCallResult:
"""Result returned by the method call wrapper."""
bus_name: str
object_path: str
interface: str
@ -164,8 +144,6 @@ class DbusMethodCallResult:
@dataclass(slots=True, frozen=True)
class DbusSignalReceiveRequest:
"""Request to receive a D-Bus signal."""
bus_name: str
object_path: str
interface: str
@ -176,8 +154,6 @@ class DbusSignalReceiveRequest:
@dataclass(slots=True, frozen=True)
class DbusSignalReceiveResult:
"""Result returned by the signal receive wrapper."""
bus_name: str
object_path: str
interface: str
@ -192,8 +168,6 @@ class DbusSignalReceiveResult:
@dataclass(slots=True, frozen=True)
class DbusPropertyReadRequest:
"""Request to read a D-Bus property."""
bus_name: str
object_path: str
interface: str
@ -204,8 +178,6 @@ class DbusPropertyReadRequest:
@dataclass(slots=True, frozen=True)
class DbusPropertyReadResult:
"""Result returned by the property read wrapper."""
bus_name: str
object_path: str
interface: str
@ -219,16 +191,12 @@ class DbusPropertyReadResult:
@dataclass(slots=True, frozen=True)
class DbusHealthCheckRequest:
"""Request to read the current backend health state."""
bus_name: str
context: WrapperCallContext | None = None
@dataclass(slots=True, frozen=True)
class DbusHealthCheckResult:
"""Result returned by the health/status wrapper."""
bus_name: str
healthy: bool
connected: bool
@ -282,4 +250,4 @@ __all__ = [
"DbusWrapperError",
"DbusWrapperStateError",
"DbusWrapperTransportError",
]
]

View File

@ -110,7 +110,7 @@ class DbusMethodCallWrapper(
request.interface,
request.member,
request.arguments,
request.keyword_arguments,
dict(request.keyword_arguments),
request.timeout_seconds,
)
return DbusMethodCallResult(
@ -233,4 +233,4 @@ __all__ = [
"DbusObjectAccessWrapper",
"DbusPropertyReadWrapper",
"DbusSignalReceiveWrapper",
]
]

View File

@ -19,7 +19,12 @@ from app.adapters.skeleton.config import (
UniversalAdapterConfigValidationError,
)
from . import FileCursorStrategy, FilePollingStrategy, FileTailProgressState, FileTailStrategy
from . import (
FileCursorStrategy,
FilePollingStrategy,
FileTailProgressState,
FileTailStrategy,
)
class FileAcquisitionStrategyKind(StrEnum):
@ -143,9 +148,9 @@ def _build_file_tail_strategy(
class FileAcquisitionStrategyRegistry:
"""Immutable registry of file acquisition strategy builders."""
builders: Mapping[FileAcquisitionStrategyKind, FileAcquisitionStrategyBuilderProtocol] = (
field(default_factory=dict)
)
builders: Mapping[
FileAcquisitionStrategyKind, FileAcquisitionStrategyBuilderProtocol
] = field(default_factory=dict)
def register_builder(
self,
@ -210,4 +215,4 @@ __all__ = [
"FileAcquisitionStrategyRegistry",
"default_file_acquisition_strategy_registry",
"resolve_file_acquisition_strategy_kind",
]
]

View File

@ -4,6 +4,7 @@ from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, cast
from app.adapters.file_adapter.acquisition.registry import (
FileAcquisitionStrategyRegistry,
@ -11,14 +12,19 @@ from app.adapters.file_adapter.acquisition.registry import (
)
from app.adapters.file_adapter.connection import FileConnectionDriver
from app.adapters.skeleton.base import (
BaseAcquisitionStrategy,
BaseAdapterFactory,
BaseConnectionDriver,
BaseMessageMarker,
BaseMessageParser,
BaseMessagePrefilter,
BaseMessageValidator,
)
from app.adapters.skeleton.config import (
AcquisitionConfig,
ConnectionConfig,
ConnectionType,
ParsingConfig,
UniversalAdapterConfig,
UniversalAdapterConfigValidationError,
)
@ -74,19 +80,42 @@ class FileAdapterFactory(
"file adapter requires connection.file to be configured"
)
acquisition_registry = self.acquisition_registry
def connection_factory(
connection_config: ConnectionConfig, /, **kwargs: Any
) -> BaseConnectionDriver[Any]:
return cast(
BaseConnectionDriver[Any],
_build_file_connection_driver(connection_config),
)
def acquisition_factory(
connection_config: ConnectionConfig,
acquisition_config: AcquisitionConfig,
/,
**kwargs: Any,
) -> BaseAcquisitionStrategy[Any]:
strategy = acquisition_registry.build(
config,
connection_config,
acquisition_config,
**kwargs,
)
return cast(BaseAcquisitionStrategy[Any], strategy)
def parser_factory(
parsing_config: ParsingConfig,
/,
**kwargs: Any,
) -> BaseMessageParser[Any, CanonicalMessage]:
parser = create_message_parser(parsing_config)
return cast(BaseMessageParser[Any, CanonicalMessage], parser)
return create_universal_adapter_runtime(
config,
connection_factory=lambda connection_config: _build_file_connection_driver(
connection_config
),
acquisition_factory=lambda connection_config, acquisition_config: (
acquisition_registry.build(
config,
connection_config,
acquisition_config,
)
),
parser_factory=lambda parsing_config: create_message_parser(parsing_config),
connection_factory=connection_factory,
acquisition_factory=acquisition_factory,
parser_factory=parser_factory,
export_port=self.export_port,
observability=self.observability,
validation=self.validation,
@ -117,9 +146,9 @@ def create_file_adapter_runtime(
validation=validation,
prefilter=prefilter,
marking=marking,
reconnect_policy=ReconnectPolicy()
if reconnect_policy is None
else reconnect_policy,
reconnect_policy=(
ReconnectPolicy() if reconnect_policy is None else reconnect_policy
),
sleeper=sleeper,
)
return factory.create(config)
@ -128,4 +157,4 @@ def create_file_adapter_runtime(
__all__ = [
"FileAdapterFactory",
"create_file_adapter_runtime",
]
]

View File

@ -1,10 +1,11 @@
"""Cursor and sequence acquisition strategy for the universal skeleton adapter."""
"""Cursor and sequence acquisition strategy specializations."""
from __future__ import annotations
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import cast
from app.adapters.skeleton.base import BaseAcquisitionStrategy, BaseConnectionDriver
from app.adapters.skeleton.model import RawMessage
@ -45,25 +46,8 @@ def _is_newer(current: ProgressValue | None, last: ProgressValue | None) -> bool
return current_rank > last_rank
def _extract_position(
message: RawMessage,
*,
position_key: str,
position_getter: Callable[[RawMessage], ProgressValue | None] | None,
) -> ProgressValue | None:
if position_getter is not None:
return _freeze_value(position_getter(message))
if isinstance(message.data, Mapping):
value = message.data.get(position_key)
if isinstance(value, (int, str)):
return _freeze_value(value)
return None
@dataclass(slots=True)
class InMemoryCursorProgressState:
"""Mutable in-memory cursor progress state."""
cursor: str | None = None
committed_at: datetime | None = None
@ -73,15 +57,12 @@ class InMemoryCursorProgressState:
def snapshot(self) -> CursorProgressSnapshot:
return CursorProgressSnapshot(
cursor=self.cursor,
committed_at=self.committed_at,
cursor=self.cursor, committed_at=self.committed_at
)
@dataclass(slots=True)
class InMemorySequenceProgressState:
"""Mutable in-memory sequence progress state."""
sequence: int | str | None = None
committed_at: datetime | None = None
@ -98,8 +79,6 @@ class InMemorySequenceProgressState:
@dataclass(slots=True)
class CursorOrSequenceReadStrategy(BaseAcquisitionStrategy[RawMessage]):
"""Read newer raw messages using a cursor or sequence progress state."""
progress_state: InMemoryCursorProgressState | InMemorySequenceProgressState
position_key: str = "position"
position_getter: Callable[[RawMessage], ProgressValue | None] | None = None
@ -116,11 +95,7 @@ class CursorOrSequenceReadStrategy(BaseAcquisitionStrategy[RawMessage]):
message = driver.receive()
if message is None:
break
position = _extract_position(
message,
position_key=self.position_key,
position_getter=self.position_getter,
)
position = self._extract_position(message)
if position is not None and not _is_newer(position, committed):
continue
messages.append(message)
@ -134,23 +109,37 @@ class CursorOrSequenceReadStrategy(BaseAcquisitionStrategy[RawMessage]):
return messages
def commit(self) -> None:
"""Commit the latest acquired position to the in-memory progress state."""
if self._pending_position is None:
return
if hasattr(self.progress_state, "cursor"):
cursor_value = self._pending_position
if cursor_value is not None and not isinstance(cursor_value, str):
cursor_value = str(cursor_value)
self.progress_state.advance(cursor_value)
cast(InMemoryCursorProgressState, self.progress_state).advance(cursor_value)
else:
self.progress_state.advance(self._pending_position)
cast(InMemorySequenceProgressState, self.progress_state).advance(
self._pending_position
)
self._pending_position = None
def _extract_position(self, message: RawMessage) -> ProgressValue | None:
if self.position_getter is not None:
position = self.position_getter(message)
return _freeze_value(position)
if isinstance(message.data, Mapping):
value = message.data.get(self.position_key)
if isinstance(value, (int, str)):
return _freeze_value(value)
return None
def _committed_position(self) -> ProgressValue | None:
if hasattr(self.progress_state, "cursor"):
return _freeze_value(self.progress_state.cursor)
return _freeze_value(self.progress_state.sequence)
return _freeze_value(
cast(InMemoryCursorProgressState, self.progress_state).cursor
)
return _freeze_value(
cast(InMemorySequenceProgressState, self.progress_state).sequence
)
__all__ = [

View File

@ -1,4 +1,4 @@
"""Acquisition models and progress contracts for the universal skeleton."""
"""Progress snapshot models and protocols for the universal skeleton."""
from __future__ import annotations
@ -147,11 +147,9 @@ class CursorProgressState(Protocol):
cursor: str | None
committed_at: datetime | None
def advance(self, cursor: str | None) -> None:
"""Advance the cursor to a new value."""
def advance(self, cursor: str | None) -> None: ...
def snapshot(self) -> CursorProgressSnapshot:
"""Return an immutable cursor progress snapshot."""
def snapshot(self) -> CursorProgressSnapshot: ...
@runtime_checkable
@ -161,11 +159,9 @@ class SequenceProgressState(Protocol):
sequence: int | str | None
committed_at: datetime | None
def advance(self, sequence: int | str | None) -> None:
"""Advance the sequence to a new value."""
def advance(self, sequence: int | str | None) -> None: ...
def snapshot(self) -> SequenceProgressSnapshot:
"""Return an immutable sequence progress snapshot."""
def snapshot(self) -> SequenceProgressSnapshot: ...
@runtime_checkable
@ -175,11 +171,9 @@ class TimestampProgressState(Protocol):
timestamp: datetime | None
committed_at: datetime | None
def advance(self, timestamp: datetime | None) -> None:
"""Advance the timestamp to a new value."""
def advance(self, timestamp: datetime | None) -> None: ...
def snapshot(self) -> TimestampProgressSnapshot:
"""Return an immutable timestamp progress snapshot."""
def snapshot(self) -> TimestampProgressSnapshot: ...
__all__ = [

View File

@ -2,6 +2,8 @@
from __future__ import annotations
from typing import TypeVar
from .errors import UniversalAdapterConfigValidationError
from .models import (
AcquisitionConfig,
@ -24,6 +26,8 @@ from .models import (
ValidationMode,
)
TConfigSection = TypeVar("TConfigSection")
class UniversalAdapterConfigValidator:
"""Validate typed config objects built from YAML or code."""
@ -55,35 +59,45 @@ class UniversalAdapterConfigValidator:
def _validate_connection(self, section: ConnectionConfig) -> None:
self._validate_enum(section.type, ConnectionType, "connection.type")
if section.type is ConnectionType.FILE:
self._require_connection_variant(section.file, "connection.file")
self._require_non_empty(section.file.path, "connection.file.path")
file_section = self._require_connection_variant(
section.file, "connection.file"
)
self._require_non_empty(file_section.path, "connection.file.path")
elif section.type is ConnectionType.UNIX_SOCKET:
self._require_connection_variant(
unix_socket_section = self._require_connection_variant(
section.unix_socket,
"connection.unix_socket",
)
self._require_non_empty(
section.unix_socket.path,
unix_socket_section.path,
"connection.unix_socket.path",
)
elif section.type is ConnectionType.HTTP:
self._require_connection_variant(section.http, "connection.http")
self._require_non_empty(section.http.url, "connection.http.url")
http_section = self._require_connection_variant(
section.http, "connection.http"
)
self._require_non_empty(http_section.url, "connection.http.url")
elif section.type is ConnectionType.API:
self._require_connection_variant(section.api, "connection.api")
self._require_non_empty(section.api.path, "connection.api.path")
api_section = self._require_connection_variant(
section.api, "connection.api"
)
self._require_non_empty(api_section.path, "connection.api.path")
elif section.type is ConnectionType.SHELL:
self._require_connection_variant(section.shell, "connection.shell")
self._require_non_empty(section.shell.command, "connection.shell.command")
shell_section = self._require_connection_variant(
section.shell, "connection.shell"
)
self._require_non_empty(shell_section.command, "connection.shell.command")
elif section.type is ConnectionType.DBUS:
self._require_connection_variant(section.dbus, "connection.dbus")
self._require_non_empty(section.dbus.bus_name, "connection.dbus.bus_name")
dbus_section = self._require_connection_variant(
section.dbus, "connection.dbus"
)
self._require_non_empty(dbus_section.bus_name, "connection.dbus.bus_name")
self._require_non_empty(
section.dbus.object_path,
dbus_section.object_path,
"connection.dbus.object_path",
)
self._require_non_empty(section.dbus.interface, "connection.dbus.interface")
self._require_non_empty(section.dbus.member, "connection.dbus.member")
self._require_non_empty(dbus_section.interface, "connection.dbus.interface")
self._require_non_empty(dbus_section.member, "connection.dbus.member")
def _validate_acquisition(self, section: AcquisitionConfig) -> None:
self._validate_enum(
@ -130,9 +144,12 @@ class UniversalAdapterConfigValidator:
f"{path} has unsupported value {value!r}"
) from exc
def _require_connection_variant(self, section: object, path: str) -> None:
def _require_connection_variant(
self, section: TConfigSection | None, path: str
) -> TConfigSection:
if section is None:
raise UniversalAdapterConfigValidationError(f"{path} must be provided")
return section
def _require_non_empty(self, value: str | None, path: str) -> None:
if value is None or not value.strip():

View File

@ -40,7 +40,6 @@ __all__ = [
"ConnectionStateError",
"ConnectionStateMachine",
"ConnectionTransportError",
"DbusConnectionDriver",
"FileConnectionDriver",
"ReconnectPolicy",
"ShellConnectionDriver",

View File

@ -5,7 +5,7 @@ from __future__ import annotations
import json
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, BinaryIO
from typing import Any, BinaryIO, Mapping
from app.adapters.skeleton.config import FileConnectionConfig
from app.adapters.skeleton.model import RawMessage
@ -127,7 +127,7 @@ class FileConnectionDriver:
finally:
self._handle = None
def _serialize_payload(self, data: bytes | str | dict[str, Any]) -> bytes:
def _serialize_payload(self, data: bytes | str | Mapping[str, Any]) -> bytes:
if isinstance(data, bytes):
return data
if isinstance(data, str):

View File

@ -5,7 +5,7 @@ from __future__ import annotations
import json
import subprocess
from dataclasses import dataclass, field
from typing import Any, BinaryIO
from typing import Any, Mapping
from app.adapters.skeleton.config import ShellConnectionConfig
from app.adapters.skeleton.model import RawMessage
@ -29,8 +29,8 @@ class ShellConnectionDriver:
_process: subprocess.Popen[bytes] | None = field(
default=None, init=False, repr=False
)
_stdin: BinaryIO | None = field(default=None, init=False, repr=False)
_stdout: BinaryIO | None = field(default=None, init=False, repr=False)
_stdin: Any | None = field(default=None, init=False, repr=False)
_stdout: Any | None = field(default=None, init=False, repr=False)
def __post_init__(self) -> None:
if not self.config.command.strip():
@ -149,7 +149,7 @@ class ShellConnectionDriver:
finally:
self._stdout = None
def _serialize_payload(self, data: bytes | str | dict[str, Any]) -> bytes:
def _serialize_payload(self, data: bytes | str | Mapping[str, Any]) -> bytes:
if isinstance(data, bytes):
return data
if isinstance(data, str):

View File

@ -5,7 +5,7 @@ from __future__ import annotations
import json
import socket
from dataclasses import dataclass, field
from typing import Any
from typing import Any, Mapping
from app.adapters.skeleton.config import UnixSocketConnectionConfig
from app.adapters.skeleton.model import RawMessage
@ -41,7 +41,12 @@ class UnixSocketConnectionDriver:
self.state_machine.mark_disconnected(reason="reset-after-failure")
self.state_machine.mark_connecting(path=self.config.path)
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
af_unix = getattr(socket, "AF_UNIX", None)
if af_unix is None:
raise ConnectionTransportError(
"unix socket transport is not supported on this platform"
)
sock = socket.socket(af_unix, socket.SOCK_STREAM)
if self.config.timeout_seconds is not None:
sock.settimeout(self.config.timeout_seconds)
sock.connect(self.config.path)
@ -116,7 +121,7 @@ class UnixSocketConnectionDriver:
if not self.is_alive():
raise ConnectionStateError("unix socket transport is not connected")
def _serialize_payload(self, data: bytes | str | dict[str, Any]) -> bytes:
def _serialize_payload(self, data: bytes | str | Mapping[str, Any]) -> bytes:
if isinstance(data, bytes):
return data
if isinstance(data, str):

View File

@ -3,6 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from google.protobuf.message import Message as ProtobufMessage
@ -17,7 +18,7 @@ class MessageExportBridge:
port: MessageExportPort
def export(self, message: object) -> None:
def export(self, message: Any) -> None:
if isinstance(message, CanonicalMessage):
self.port.export(canonical_message_to_proto(message))
return

View File

@ -88,9 +88,9 @@ def create_universal_adapter_runtime(
validation=validation,
prefilter=prefilter,
marking=marking,
reconnect_policy=ReconnectPolicy()
if reconnect_policy is None
else reconnect_policy,
reconnect_policy=(
ReconnectPolicy() if reconnect_policy is None else reconnect_policy
),
sleeper=sleeper,
)
return factory.create(config)

View File

@ -17,7 +17,7 @@ def _freeze_mapping(value: Mapping[str, Any]) -> Mapping[str, Any]:
class RawMessage:
"""Raw transport-level message before parsing."""
data: bytes | str | Mapping[str, Any]
data: Any
source: str
transport: str | None = None
received_at: datetime | None = None

View File

@ -18,8 +18,7 @@ from .text import TextMessageParser
class ParserBuilderProtocol(Protocol):
"""Callable that builds a parser from parsing config."""
def __call__(self, config: Any, /, **kwargs: Any) -> MessageParserBase:
"""Build a parser for the given config."""
def __call__(self, config: Any, /, **kwargs: Any) -> MessageParserBase: ...
def _normalize_parser_kind(value: ParserKind | str) -> ParserKind:

View File

@ -156,8 +156,7 @@ class ConnectionFactoryProtocol(Protocol):
config: ConnectionConfig,
/,
**kwargs: Any,
) -> BaseConnectionDriver[Any]:
"""Build a connection driver."""
) -> BaseConnectionDriver[Any]: ...
@runtime_checkable
@ -170,8 +169,7 @@ class AcquisitionFactoryProtocol(Protocol):
acquisition: AcquisitionConfig,
/,
**kwargs: Any,
) -> BaseAcquisitionStrategy[Any]:
"""Build an acquisition strategy."""
) -> BaseAcquisitionStrategy[Any]: ...
@runtime_checkable
@ -183,8 +181,7 @@ class ParserFactoryProtocol(Protocol):
config: ParsingConfig,
/,
**kwargs: Any,
) -> BaseMessageParser[Any, CanonicalMessage]:
"""Build a message parser."""
) -> BaseMessageParser[Any, CanonicalMessage]: ...
def _noop_sleep(_: float) -> None:
@ -348,7 +345,7 @@ class UniversalAdapterRuntime(BaseAdapterRuntime):
if self.connection_driver is None:
raise RuntimeError("connection driver has not been built")
delays = iter_reconnect_delays(self.reconnect_policy)
delays = iter(iter_reconnect_delays(self.reconnect_policy))
attempt = 0
while True:
try:
@ -473,7 +470,6 @@ class UniversalAdapterRuntime(BaseAdapterRuntime):
if callable(commit):
commit()
def _publish_status(self) -> None:
assert self.observability is not None
snapshot = self.observability.build_status_snapshot(
@ -511,4 +507,3 @@ __all__ = [
"RuntimeTransitionError",
"UniversalAdapterRuntime",
]

View File

@ -14,7 +14,12 @@ from .acquisition import (
from .connection import WpaSupplicantConnectionDriver
from .factory import WpaSupplicantAdapterFactory, create_wpa_supplicant_adapter_runtime
from .model import WpaSourceChannel, WpaSourceDescriptor, file_descriptor
from .parsing import WpaConfigParser, WpaCtrlIfaceParser, WpaEventTextParser, WpaStatusParser
from .parsing import (
WpaConfigParser,
WpaCtrlIfaceParser,
WpaEventTextParser,
WpaStatusParser,
)
__all__ = [
"WpaConfigParser",
@ -36,4 +41,4 @@ __all__ = [
"WpaSupplicantConnectionDriver",
"create_wpa_supplicant_adapter_runtime",
"file_descriptor",
]
]

View File

@ -5,7 +5,7 @@ from __future__ import annotations
from collections.abc import Iterable
from app.adapters.skeleton.acquisition import PollingReadStrategy
from app.adapters.skeleton.base import BaseAcquisitionStrategy
from app.adapters.skeleton.base import BaseAcquisitionStrategy, BaseConnectionDriver
from app.adapters.skeleton.model import RawMessage
from app.adapters.wpa_supplicant_adapter.connection import (
WpaSupplicantConnectionDriver,
@ -27,14 +27,14 @@ class WpaSourceAcquisitionStrategy(BaseAcquisitionStrategy[RawMessage]):
expected_channels: tuple[WpaSourceChannel, ...] = ()
strategy_name: str = "source"
def acquire(self, driver: WpaSupplicantConnectionDriver) -> Iterable[RawMessage]:
def acquire(self, driver: BaseConnectionDriver[RawMessage]) -> Iterable[RawMessage]:
self._ensure_driver(driver)
if not driver.is_alive():
return []
message = driver.receive()
return [] if message is None else [message]
def _ensure_driver(self, driver: WpaSupplicantConnectionDriver) -> None:
def _ensure_driver(self, driver: BaseConnectionDriver[RawMessage]) -> None:
if not isinstance(driver, WpaSupplicantConnectionDriver):
raise WpaSupplicantAcquisitionConfigurationError(
f"{self.strategy_name} requires a WpaSupplicantConnectionDriver"

View File

@ -67,8 +67,8 @@ def _build_event_strategy(
class WpaAcquisitionStrategyRegistry:
"""Immutable registry of WPA acquisition strategy builders."""
builders: Mapping[WpaSourceChannel, WpaAcquisitionStrategyBuilderProtocol] = (
field(default_factory=dict)
builders: Mapping[WpaSourceChannel, WpaAcquisitionStrategyBuilderProtocol] = field(
default_factory=dict
)
def register_builder(
@ -109,8 +109,12 @@ def default_wpa_acquisition_strategy_registry() -> WpaAcquisitionStrategyRegistr
WpaSourceChannel.CTRL_IFACE,
_build_ctrl_iface_strategy,
)
registry = registry.register_builder(WpaSourceChannel.CONFIG, _build_config_strategy)
registry = registry.register_builder(WpaSourceChannel.STATUS, _build_status_strategy)
registry = registry.register_builder(
WpaSourceChannel.CONFIG, _build_config_strategy
)
registry = registry.register_builder(
WpaSourceChannel.STATUS, _build_status_strategy
)
registry = registry.register_builder(WpaSourceChannel.EVENT, _build_event_strategy)
return registry
@ -119,4 +123,4 @@ __all__ = [
"WpaAcquisitionStrategyBuilderProtocol",
"WpaAcquisitionStrategyRegistry",
"default_wpa_acquisition_strategy_registry",
]
]

View File

@ -168,9 +168,11 @@ class WpaSupplicantConnectionDriver(BaseConnectionDriver[RawMessage]):
"identifier": self.descriptor.identifier,
"source_uri": self.descriptor.source_uri,
"interface_name": self.interface_name,
"path": str(self._resolve_path())
if self.descriptor.channel is not WpaSourceChannel.CTRL_IFACE
else None,
"path": (
str(self._resolve_path())
if self.descriptor.channel is not WpaSourceChannel.CTRL_IFACE
else None
),
"receive_command": self.receive_command,
"state": self.state_machine.state.value,
}

View File

@ -4,10 +4,14 @@ from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, cast
from app.adapters.skeleton.base import (
BaseAcquisitionStrategy,
BaseAdapterFactory,
BaseConnectionDriver,
BaseMessageMarker,
BaseMessageParser,
BaseMessagePrefilter,
BaseMessageValidator,
)
@ -25,9 +29,7 @@ from app.adapters.wpa_supplicant_adapter.acquisition.registry import (
from app.adapters.wpa_supplicant_adapter.connection import (
WpaSupplicantConnectionDriver,
)
from app.adapters.wpa_supplicant_adapter.model import (
WpaSourceDescriptor,
)
from app.adapters.wpa_supplicant_adapter.model import WpaSourceDescriptor
from app.adapters.wpa_supplicant_adapter.parsing.registry import (
WpaParserRegistry,
default_wpa_parser_registry,
@ -44,8 +46,8 @@ def _noop_sleep(_: float) -> None:
def _build_connection_factory(
descriptor: WpaSourceDescriptor,
backend: WpaWrapperBackend,
) -> Callable[[object], WpaSupplicantConnectionDriver]:
def factory(_: object) -> WpaSupplicantConnectionDriver:
) -> Callable[[Any], WpaSupplicantConnectionDriver]:
def factory(_: Any, /, **kwargs: Any) -> WpaSupplicantConnectionDriver:
return WpaSupplicantConnectionDriver(descriptor=descriptor, backend=backend)
return factory
@ -69,19 +71,47 @@ class WpaSupplicantAdapterFactory(
acquisition_registry: WpaAcquisitionStrategyRegistry = field(
default_factory=default_wpa_acquisition_strategy_registry
)
parser_registry: WpaParserRegistry = field(default_factory=default_wpa_parser_registry)
parser_registry: WpaParserRegistry = field(
default_factory=default_wpa_parser_registry
)
def create(self, config: UniversalAdapterConfig) -> UniversalAdapterRuntime:
acquisition_registry = self.acquisition_registry
parser_registry = self.parser_registry
def connection_factory(
connection_config: Any, /, **kwargs: Any
) -> BaseConnectionDriver[Any]:
return cast(
BaseConnectionDriver[Any],
_build_connection_factory(self.source_descriptor, self.backend)(
connection_config,
**kwargs,
),
)
def acquisition_factory(
_connection_config: Any,
_acquisition_config: Any,
/,
**kwargs: Any,
) -> BaseAcquisitionStrategy[Any]:
strategy = acquisition_registry.build(self.source_descriptor, **kwargs)
return cast(BaseAcquisitionStrategy[Any], strategy)
def parser_factory(
_parsing_config: Any,
/,
**kwargs: Any,
) -> BaseMessageParser[Any, CanonicalMessage]:
parser = parser_registry.build(self.source_descriptor, **kwargs)
return cast(BaseMessageParser[Any, CanonicalMessage], parser)
return UniversalAdapterRuntime(
config=config,
connection_factory=_build_connection_factory(
self.source_descriptor,
self.backend,
),
acquisition_factory=lambda _connection_config, _acquisition_config: acquisition_registry.build(self.source_descriptor),
parser_factory=lambda _: parser_registry.build(self.source_descriptor),
connection_factory=connection_factory,
acquisition_factory=acquisition_factory,
parser_factory=parser_factory,
export_port=self.export_port,
observability=self.observability,
validation=self.validation or ValidationStub(self.observability),
@ -116,9 +146,9 @@ def create_wpa_supplicant_adapter_runtime(
validation=validation,
prefilter=prefilter,
marking=marking,
reconnect_policy=ReconnectPolicy()
if reconnect_policy is None
else reconnect_policy,
reconnect_policy=(
ReconnectPolicy() if reconnect_policy is None else reconnect_policy
),
sleeper=sleeper,
)
return factory.create(config)
@ -127,4 +157,4 @@ def create_wpa_supplicant_adapter_runtime(
__all__ = [
"WpaSupplicantAdapterFactory",
"create_wpa_supplicant_adapter_runtime",
]
]

View File

@ -114,4 +114,4 @@ __all__ = [
"WpaParserBuilderProtocol",
"WpaParserRegistry",
"default_wpa_parser_registry",
]
]

View File

@ -38,4 +38,4 @@ __all__ = [
"WpaWrapperError",
"WpaWrapperStateError",
"WpaWrapperTransportError",
]
]

View File

@ -37,21 +37,17 @@ class WpaWrapperBackend(Protocol):
command: str,
arguments: tuple[str, ...],
timeout_seconds: float | None = None,
) -> str | Mapping[str, Any]:
"""Execute a ctrl_iface request and return the backend response."""
) -> str | Mapping[str, Any]: ...
def read_path(
self,
path: str | Path,
timeout_seconds: float | None = None,
) -> str:
"""Read a config/status/event path as text."""
) -> str: ...
@dataclass(slots=True, frozen=True)
class WpaCtrlIfaceRequest:
"""Request a ctrl_iface command/response roundtrip."""
interface_name: str
command: str
arguments: tuple[str, ...] = ()
@ -61,8 +57,6 @@ class WpaCtrlIfaceRequest:
@dataclass(slots=True, frozen=True)
class WpaCtrlIfaceResult:
"""Response returned by the ctrl_iface wrapper."""
interface_name: str
command: str
ok: bool
@ -75,8 +69,6 @@ class WpaCtrlIfaceResult:
@dataclass(slots=True, frozen=True)
class WpaFileReadRequest:
"""Request to read a wpa_supplicant-related file path."""
path: str | Path
timeout_seconds: float | None = None
context: WrapperCallContext | None = None
@ -84,8 +76,6 @@ class WpaFileReadRequest:
@dataclass(slots=True, frozen=True)
class WpaFileReadResult:
"""Response returned by a file read wrapper."""
path: Path
data: str
details: Mapping[str, Any] = field(default_factory=dict)
@ -145,4 +135,4 @@ __all__ = [
"WpaWrapperError",
"WpaWrapperStateError",
"WpaWrapperTransportError",
]
]

View File

@ -124,4 +124,4 @@ __all__ = [
"WpaFileReadWrapper",
"WpaStatusPollingWrapper",
"WpaStatusReadWrapper",
]
]

View File

@ -6,13 +6,41 @@ from dataclasses import dataclass
from sys import stdout
from typing import BinaryIO
from google.protobuf.internal.decoder import _DecodeVarint32
from google.protobuf.internal.encoder import _VarintBytes
from google.protobuf.message import Message as ProtobufMessage
from app.shared.contracts import MessageExportPort
def _encode_varint(value: int) -> bytes:
if value < 0:
raise ValueError("varint value must be non-negative")
encoded = bytearray()
while True:
to_write = value & 0x7F
value >>= 7
if value:
encoded.append(to_write | 0x80)
continue
encoded.append(to_write)
return bytes(encoded)
def _decode_varint(data: bytes, index: int) -> tuple[int, int]:
shift = 0
value = 0
while True:
if index >= len(data):
raise ValueError("truncated varint frame")
byte = data[index]
index += 1
value |= (byte & 0x7F) << shift
if not byte & 0x80:
return value, index
shift += 7
if shift >= 64:
raise ValueError("varint frame is too large")
@dataclass(slots=True)
class StdoutProtoMessageDirector(MessageExportPort):
"""Serialize protobuf wire messages and write them to stdout as frames."""
@ -21,7 +49,7 @@ class StdoutProtoMessageDirector(MessageExportPort):
def export(self, message: ProtobufMessage) -> None:
payload = message.SerializeToString()
self.stream.write(_VarintBytes(len(payload)))
self.stream.write(_encode_varint(len(payload)))
self.stream.write(payload)
self.stream.flush()
@ -34,10 +62,10 @@ def read_framed_messages(stream: BinaryIO) -> list[bytes]:
index = 0
data_len = len(data)
while index < data_len:
size, next_index = _DecodeVarint32(data, index)
frame = data[next_index : next_index + size]
size, index = _decode_varint(data, index)
frame = data[index : index + size]
frames.append(frame)
index = next_index + size
index += size
return frames

View File

@ -56,16 +56,14 @@ StatusSnapshot = AdapterStatusSnapshot
class MessageExportPort(Protocol):
"""Port used by an adapter to hand off protobuf wire messages to a sink."""
def export(self, message: ProtobufMessage) -> None:
"""Export one message object."""
def export(self, message: ProtobufMessage) -> None: ...
@runtime_checkable
class ObservabilityPort(Protocol):
"""Port used by an adapter to publish traces, metrics, and snapshots."""
def emit_trace(self, event: object) -> None:
"""Publish a trace event."""
def emit_trace(self, event: object) -> None: ...
def increment_metric(
self,
@ -73,16 +71,13 @@ class ObservabilityPort(Protocol):
value: int | float = 1,
*,
tags: Mapping[str, str] | None = None,
) -> None:
"""Record a metric increment or gauge update."""
) -> None: ...
def update_status(self, snapshot: StatusSnapshot) -> None:
"""Publish a new status snapshot."""
def update_status(self, snapshot: StatusSnapshot) -> None: ...
@runtime_checkable
class StatusSnapshotPort(Protocol):
"""Port for reading the current adapter status snapshot."""
def snapshot(self) -> StatusSnapshot:
"""Return the latest status snapshot."""
def snapshot(self) -> StatusSnapshot: ...

View File

@ -129,18 +129,24 @@ class InMemoryObservabilityService(ObservabilityPort, StatusSnapshotPort):
return StatusSnapshotBuilder(
adapter_id=builder.adapter_id,
state=builder.state if state is None else state,
connection_state=builder.connection_state
if connection_state is None
else connection_state,
last_received_at=builder.last_received_at
if last_received_at is None
else last_received_at,
last_exported_at=builder.last_exported_at
if last_exported_at is None
else last_exported_at,
last_command_at=builder.last_command_at
if last_command_at is None
else last_command_at,
connection_state=(
builder.connection_state
if connection_state is None
else connection_state
),
last_received_at=(
builder.last_received_at
if last_received_at is None
else last_received_at
),
last_exported_at=(
builder.last_exported_at
if last_exported_at is None
else last_exported_at
),
last_command_at=(
builder.last_command_at if last_command_at is None else last_command_at
),
details=builder.details if details is None else details,
).build(
details={

View File

@ -6,11 +6,11 @@ from pathlib import Path
import pytest
from app.adapters.base import AcquisitionStrategy
from app.adapters.skeleton.acquisition import (
AcquisitionCompatibilityError,
AcquisitionStrategyKind,
AcquisitionStrategyRegistry,
CursorOrSequenceReadStrategy,
FileTailReadStrategy,
InMemoryCursorProgressState,
InMemorySequenceProgressState,
@ -20,6 +20,7 @@ from app.adapters.skeleton.acquisition import (
resolve_acquisition_strategy_kind,
validate_acquisition_strategy_compatibility,
)
from app.adapters.skeleton.base import BaseAcquisitionStrategy, BaseConnectionDriver
from app.adapters.skeleton.config import (
AcquisitionConfig,
AcquisitionDetectionConfig,
@ -37,18 +38,24 @@ from app.adapters.skeleton.model import RawMessage
DATA_ROOT = Path(__file__).resolve().parents[1] / ".tmp" / "acquisition_factory"
class DummyStrategy:
class DummyStrategy(BaseAcquisitionStrategy[RawMessage]):
def __init__(self) -> None:
self.messages: list[RawMessage] = []
def acquire(self, driver):
def acquire(self, driver: BaseConnectionDriver[RawMessage]):
return []
class DummyDriver:
class DummyDriver(BaseConnectionDriver[RawMessage]):
def __init__(self, path: Path) -> None:
self.path = path
def connect(self) -> None:
return None
def disconnect(self) -> None:
return None
def is_alive(self) -> bool:
return True
@ -97,7 +104,7 @@ def test_factory_creates_polling_strategy_by_default():
strategy = create_acquisition_strategy(connection, acquisition)
assert isinstance(strategy, PollingReadStrategy)
assert isinstance(strategy, AcquisitionStrategy)
assert isinstance(strategy, BaseAcquisitionStrategy)
def test_factory_creates_cursor_sequence_strategy_for_progress_commit():
@ -109,7 +116,8 @@ def test_factory_creates_cursor_sequence_strategy_for_progress_commit():
strategy = create_acquisition_strategy(connection, acquisition)
assert isinstance(strategy, AcquisitionStrategy)
assert isinstance(strategy, CursorOrSequenceReadStrategy)
assert isinstance(strategy, BaseAcquisitionStrategy)
assert isinstance(strategy.progress_state, InMemoryCursorProgressState)
assert strategy.position_key == "offset"
@ -123,7 +131,8 @@ def test_factory_creates_sequence_strategy_for_sequence_detection():
strategy = create_acquisition_strategy(connection, acquisition)
assert isinstance(strategy, AcquisitionStrategy)
assert isinstance(strategy, CursorOrSequenceReadStrategy)
assert isinstance(strategy, BaseAcquisitionStrategy)
assert isinstance(strategy.progress_state, InMemorySequenceProgressState)
assert strategy.position_key == "offset"

View File

@ -8,9 +8,7 @@ from app.adapters.skeleton.config import UniversalAdapterConfigLoader
EXAMPLES = [
Path("src/app/adapters/skeleton/config/examples/file_polling_json.yaml"),
Path(
"src/app/adapters/skeleton/config/examples/file_polling_json_runtime.yaml"
),
Path("src/app/adapters/skeleton/config/examples/file_polling_json_runtime.yaml"),
Path("src/app/adapters/skeleton/config/examples/file_cursor_sequence.yaml"),
Path(
"src/app/adapters/skeleton/config/examples/unix_socket_stream_placeholder.yaml"

View File

@ -3,6 +3,7 @@
from __future__ import annotations
from pathlib import Path
from typing import Any, cast
import pytest
@ -132,8 +133,8 @@ def test_validator_rejects_manual_invalid_config():
type=ConnectionType.FILE,
file=FileConnectionConfig(path="/tmp/inbox.log"),
),
validation=ValidationConfig(mode="invalid"),
validation=ValidationConfig(mode=cast(Any, "invalid")),
)
with pytest.raises(UniversalAdapterConfigValidationError):
validator.validate(config)
validator.validate(config)

View File

@ -201,8 +201,9 @@ def test_concrete_adapter_factories_reuse_the_skeleton_runtime(tmp_path: Path) -
status_builder=StatusSnapshotBuilder(adapter_id="wpa-cross-adapter")
)
file_export_port = RecordingExportPort()
file_factory = FileAdapterFactory(
export_port=RecordingExportPort(),
export_port=file_export_port,
observability=file_observability,
)
dbus_backend = FakeDbusBackend(
@ -215,16 +216,18 @@ def test_concrete_adapter_factories_reuse_the_skeleton_runtime(tmp_path: Path) -
}
]
)
dbus_export_port = RecordingExportPort()
dbus_factory = DBusAdapterFactory(
export_port=RecordingExportPort(),
export_port=dbus_export_port,
observability=dbus_observability,
backend_factory=lambda _config: dbus_backend,
)
wpa_backend = FakeWpaBackend()
wpa_export_port = RecordingExportPort()
wpa_factory = WpaSupplicantAdapterFactory(
source_descriptor=file_descriptor(WpaSourceChannel.STATUS, status_path),
backend=wpa_backend,
export_port=RecordingExportPort(),
export_port=wpa_export_port,
observability=wpa_observability,
)
@ -250,9 +253,9 @@ def test_concrete_adapter_factories_reuse_the_skeleton_runtime(tmp_path: Path) -
assert dbus_observability.counters["messages_out_total"] == 1
assert wpa_observability.counters["messages_out_total"] == 1
assert file_runtime.export_port.messages
assert dbus_runtime.export_port.messages
assert wpa_runtime.export_port.messages
assert file_export_port.messages
assert dbus_export_port.messages
assert wpa_export_port.messages
@pytest.mark.parametrize(

View File

@ -35,7 +35,7 @@ from app.adapters.skeleton.config import (
UniversalAdapterConfig,
UniversalAdapterConfigValidationError,
)
from app.adapters.skeleton.model import RawMessage
from app.adapters.skeleton.model import CanonicalMessage, RawMessage
from app.director.stdout_json import StdoutJsonMessageDirector
from app.shared.contracts import MessageExportPort
from app.shared.contracts.proto.v1 import (
@ -49,13 +49,12 @@ from app.shared.observability import InMemoryObservabilityService, StatusSnapsho
@dataclass(slots=True)
class RecordingExportPort(MessageExportPort):
messages: list[object] = field(default_factory=list)
messages: list[CanonicalMessage] = field(default_factory=list)
def export(self, message: object) -> None:
if isinstance(message, wire.CanonicalMessage):
self.messages.append(canonical_message_from_proto(message))
return
self.messages.append(message)
if not isinstance(message, wire.CanonicalMessage):
raise TypeError('expected wire.CanonicalMessage')
self.messages.append(canonical_message_from_proto(message))
@dataclass
@ -258,6 +257,7 @@ def test_dbus_cursor_like_strategy_commits_sequence_progress() -> None:
messages = list(strategy.acquire(driver))
strategy.commit()
assert isinstance(strategy.progress_state, InMemorySequenceProgressState)
assert [message.data["sequence"] for message in messages] == [1, 2]
assert strategy.progress_state.sequence == 2
@ -268,6 +268,7 @@ def test_dbus_cursor_like_strategy_commits_sequence_progress() -> None:
messages = list(strategy.acquire(driver))
strategy.commit()
assert isinstance(strategy.progress_state, InMemorySequenceProgressState)
assert [message.data["sequence"] for message in messages] == [3]
assert strategy.progress_state.sequence == 3
@ -306,8 +307,9 @@ def test_dbus_adapter_factory_runs_stream_json_runtime() -> None:
observability = InMemoryObservabilityService(
status_builder=StatusSnapshotBuilder(adapter_id="dbus-factory")
)
export_port = RecordingExportPort()
factory = DBusAdapterFactory(
export_port=RecordingExportPort(),
export_port=export_port,
observability=observability,
backend_factory=lambda config: backend,
)
@ -335,8 +337,8 @@ def test_dbus_adapter_factory_runs_stream_json_runtime() -> None:
assert backend.connect_calls == [("org.example.Service", 2.0)]
assert snapshot.adapter_id == "dbus-factory"
assert snapshot.details["handled_messages"] == 1
assert runtime.export_port.messages[0].envelope.source == "dbus-sensor"
assert runtime.export_port.messages[0].payload.data == {"value": 42}
assert export_port.messages[0].envelope.source == "dbus-sensor"
assert export_port.messages[0].payload.data == {"value": 42}
def test_dbus_adapter_factory_rejects_non_dbus_config() -> None:

View File

@ -14,6 +14,7 @@ from app.adapters.file_adapter.acquisition import (
from app.adapters.file_adapter.connection import FileConnectionDriver
from app.adapters.skeleton.acquisition import (
CursorOrSequenceReadStrategy,
InMemoryCursorProgressState,
PollingReadStrategy,
)
from app.adapters.skeleton.base import BaseConnectionDriver
@ -98,6 +99,7 @@ def test_file_cursor_strategy_defaults_to_offset_positions() -> None:
next_messages = list(strategy.acquire(driver))
assert isinstance(strategy, CursorOrSequenceReadStrategy)
assert isinstance(strategy.progress_state, InMemoryCursorProgressState)
assert strategy.position_key == "offset"
assert len(messages) == 2
assert strategy.progress_state.cursor == "2"

View File

@ -8,6 +8,7 @@ from app.adapters.skeleton.acquisition import (
FileTailReadStrategy,
InMemoryTailProgressState,
)
from app.adapters.skeleton.base import BaseConnectionDriver
from app.adapters.skeleton.config import FileConnectionConfig
from app.adapters.skeleton.connection import FileConnectionDriver
from app.adapters.skeleton.model import RawMessage
@ -15,10 +16,16 @@ from app.adapters.skeleton.model import RawMessage
DATA_ROOT = Path(__file__).resolve().parents[1] / ".tmp" / "file_tail_strategy"
class DummyDriver:
class DummyDriver(BaseConnectionDriver[RawMessage]):
def __init__(self, path: Path) -> None:
self.path = path
def connect(self) -> None:
return None
def disconnect(self) -> None:
return None
def transport_metadata(self) -> dict[str, object]:
return {"path": str(self.path)}
@ -81,7 +88,13 @@ def test_file_tail_strategy_rejects_missing_path_metadata():
progress_state = InMemoryTailProgressState(sequence=0)
strategy = FileTailReadStrategy(progress_state=progress_state)
class NoPathDriver:
class NoPathDriver(BaseConnectionDriver[RawMessage]):
def connect(self) -> None:
return None
def disconnect(self) -> None:
return None
def is_alive(self) -> bool:
return True

View File

@ -2,6 +2,8 @@
from __future__ import annotations
from typing import Any, cast
import pytest
from tests.conftest import _reject_external_markers
@ -20,8 +22,12 @@ class _FakeItem:
def test_external_marker_is_rejected():
with pytest.raises(pytest.UsageError):
_reject_external_markers([_FakeItem("tests/test_demo.py::test_case", True)])
_reject_external_markers(
cast(Any, [_FakeItem("tests/test_demo.py::test_case", True)])
)
def test_non_external_items_pass():
_reject_external_markers([_FakeItem("tests/test_demo.py::test_case", False)])
_reject_external_markers(
cast(Any, [_FakeItem("tests/test_demo.py::test_case", False)])
)

View File

@ -4,14 +4,21 @@ from __future__ import annotations
from dataclasses import dataclass, field
from google.protobuf.message import Message as ProtobufMessage
from app.adapters.skeleton.base import (
BaseAcquisitionStrategy,
BaseConnectionDriver,
BaseMessageParser,
)
from app.adapters.skeleton.config import UniversalAdapterConfig
from app.adapters.skeleton.model import CanonicalMessage, Envelope, Payload, RawMessage
from google.protobuf.message import Message as ProtobufMessage
from app.adapters.skeleton.runtime import UniversalAdapterRuntime
from app.shared.contracts import MessageExportPort
@dataclass(slots=True)
class FakeConnectionDriver:
class FakeConnectionDriver(BaseConnectionDriver[RawMessage]):
connected: bool = False
def connect(self) -> None:
@ -31,11 +38,11 @@ class FakeConnectionDriver:
@dataclass(slots=True)
class FakeAcquisitionStrategy:
class FakeAcquisitionStrategy(BaseAcquisitionStrategy[RawMessage]):
messages: list[RawMessage]
commit_called: bool = False
def acquire(self, driver: FakeConnectionDriver) -> list[RawMessage]:
def acquire(self, driver: BaseConnectionDriver[RawMessage]) -> list[RawMessage]:
return list(self.messages)
def commit(self) -> None:
@ -43,21 +50,21 @@ class FakeAcquisitionStrategy:
@dataclass(slots=True)
class RecordingExportPort:
class RecordingExportPort(MessageExportPort):
messages: list[object] = field(default_factory=list)
def export(self, message: object) -> None:
def export(self, message: ProtobufMessage) -> None:
self.messages.append(message)
@dataclass(slots=True)
class FailingExportPort:
def export(self, message: object) -> None:
class FailingExportPort(MessageExportPort):
def export(self, message: ProtobufMessage) -> None:
raise RuntimeError("boom")
@dataclass(slots=True)
class FakeParser:
class FakeParser(BaseMessageParser[RawMessage, CanonicalMessage]):
def parse(self, message: RawMessage) -> CanonicalMessage:
return CanonicalMessage(
envelope=Envelope(source=message.source),
@ -69,17 +76,17 @@ class FakeParser:
def _runtime(
*,
acquisition_strategy: FakeAcquisitionStrategy,
export_port: object,
export_port: MessageExportPort,
) -> UniversalAdapterRuntime:
driver = FakeConnectionDriver()
def connection_factory(config):
def connection_factory(config, **kwargs):
return driver
def acquisition_factory(connection_config, acquisition_config):
def acquisition_factory(connection_config, acquisition_config, **kwargs):
return acquisition_strategy
def parser_factory(parsing_config):
def parser_factory(parsing_config, **kwargs):
return FakeParser()
return UniversalAdapterRuntime(

View File

@ -52,6 +52,7 @@ def test_shell_connection_driver_round_trip():
greeting = driver.receive()
assert greeting is not None
assert isinstance(greeting.data, bytes)
assert greeting.data.replace(b"\r\n", b"\n") == b"hello\n"
assert greeting.source == sys.executable
assert greeting.transport == "shell"
@ -60,6 +61,7 @@ def test_shell_connection_driver_round_trip():
response = driver.receive()
assert response is not None
assert isinstance(response.data, bytes)
assert response.data.replace(b"\r\n", b"\n") == b'ack:{"action":"ping"}\n'
driver.disconnect()

View File

@ -1,4 +1,4 @@
"""Tests for the universal skeleton base interfaces and abstract classes."""
"""Tests for shared adapter stage interfaces."""
from __future__ import annotations

View File

@ -13,12 +13,12 @@ from app.adapters.skeleton.acquisition.models import (
CursorProgressState,
SequenceProgressState,
)
from app.adapters.skeleton.base import BaseAcquisitionStrategy
from app.adapters.skeleton.base import BaseAcquisitionStrategy, BaseConnectionDriver
from app.adapters.skeleton.model import RawMessage
@dataclass
class FakeCursorDriver:
class FakeCursorDriver(BaseConnectionDriver[RawMessage]):
inbox: list[RawMessage]
connected: bool = True
receives: int = 0
@ -50,11 +50,15 @@ def _message(position: int, payload: str) -> RawMessage:
return RawMessage(data={"position": position, "payload": payload}, source="src")
def _message_data(message: RawMessage) -> dict[str, object]:
assert isinstance(message.data, dict)
return message.data
def _cursor_position(message: RawMessage) -> str | None:
if isinstance(message.data, dict):
cursor = message.data.get("cursor")
if isinstance(cursor, str):
return cursor
cursor = _message_data(message).get("cursor")
if isinstance(cursor, str):
return cursor
return None
@ -74,7 +78,7 @@ def test_cursor_strategy_filters_stale_messages_and_commits_after_export():
messages = list(strategy.acquire(driver))
assert [message.data["payload"] for message in messages] == ["fresh"]
assert [_message_data(message)["payload"] for message in messages] == ["fresh"]
assert progress_state.cursor == "10"
assert progress_state.committed_at is None
@ -101,7 +105,10 @@ def test_sequence_strategy_accepts_numeric_progress_and_commits_latest_position(
assert isinstance(progress_state, SequenceProgressState)
messages = list(strategy.acquire(driver))
assert [message.data["payload"] for message in messages] == ["second", "third"]
assert [_message_data(message)["payload"] for message in messages] == [
"second",
"third",
]
strategy.commit()
@ -123,7 +130,7 @@ def test_cursor_strategy_can_use_custom_position_getter():
)
messages = list(strategy.acquire(driver))
assert [message.data["cursor"] for message in messages] == ["a-2"]
assert [_message_data(message)["cursor"] for message in messages] == ["a-2"]
strategy.commit()
assert progress_state.cursor == "a-2"

View File

@ -3,8 +3,11 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from app.adapters.skeleton.acquisition import CursorOrSequenceReadStrategy
from app.adapters.skeleton.base import (
BaseAcquisitionStrategy,
BaseConnectionDriver,
BaseMessageMarker,
BaseMessageParser,
@ -97,6 +100,14 @@ class PassthroughMarker(BaseMessageMarker[CanonicalMessage]):
return message
class _AcquisitionStub(BaseAcquisitionStrategy[RawMessage]):
def acquire(self, driver: BaseConnectionDriver[RawMessage]):
if driver.is_alive():
message = driver.receive()
return [] if message is None else [message]
return []
def _config() -> UniversalAdapterConfig:
return UniversalAdapterConfig(
adapter=AdapterSectionConfig(adapter_id="factory-1"),
@ -123,9 +134,7 @@ def test_universal_adapter_factory_builds_runtime_from_injected_pieces() -> None
)
factory = UniversalAdapterFactory(
connection_factory=lambda config, **kwargs: connection,
acquisition_factory=lambda connection_config, acquisition_config, **kwargs: (
_AcquisitionStub()
),
acquisition_factory=lambda connection_config, acquisition_config, **kwargs: _AcquisitionStub(),
parser_factory=lambda config, **kwargs: RecordingParser(),
export_port=export_port,
observability=observability,
@ -141,27 +150,18 @@ def test_universal_adapter_factory_builds_runtime_from_injected_pieces() -> None
handled = runtime.run_once()
assert handled == 1
assert isinstance(export_port.messages[0], CanonicalMessage)
assert export_port.messages[0].payload.data == "payload"
assert observability.counters["messages_in_total"] == 1
class _AcquisitionStub:
def acquire(self, driver: BaseConnectionDriver[RawMessage]):
if driver.is_alive():
message = driver.receive()
return [] if message is None else [message]
return []
def test_create_universal_adapter_runtime_helper_uses_same_composition_path() -> None:
connection = RecordingConnectionDriver()
export_port = RecordingExportPort()
runtime = create_universal_adapter_runtime(
_config(),
connection_factory=lambda config, **kwargs: connection,
acquisition_factory=lambda connection_config, acquisition_config, **kwargs: (
_AcquisitionStub()
),
acquisition_factory=lambda connection_config, acquisition_config, **kwargs: _AcquisitionStub(),
parser_factory=lambda config, **kwargs: RecordingParser(),
export_port=export_port,
validation=PassthroughValidator(),

View File

@ -59,7 +59,7 @@ class FakeStructuredParser(MessageParserBase):
class FakeTextParser(MessageParserBase):
def parse(self, message: RawMessage):
if not isinstance(message.data, (bytes, str)):
self.unsupported_format(path="raw.data", expected="text")
self.unsupported_format(path="raw.data", expected="bytes or text")
text = self.decode_text(message.data, encoding=message.encoding or "utf-8")
envelope = Envelope(source=message.source, received_at=message.received_at)
payload = Payload(data=text, encoding=message.encoding or "utf-8")

View File

@ -2,6 +2,8 @@
from __future__ import annotations
from typing import Any, cast
import pytest
from app.adapters.skeleton.config import ParserKind, ParsingConfig
@ -60,7 +62,7 @@ def test_parser_factory_auto_defaults_to_text_when_content_type_is_unknown():
def test_parser_factory_rejects_invalid_kind_value():
with pytest.raises(ParserConfigurationError):
create_message_parser(ParsingConfig(kind="binary"))
create_message_parser(ParsingConfig(kind=cast(Any, "binary")))
def test_parser_factory_rejects_missing_builder_in_custom_registry():
@ -75,7 +77,9 @@ def test_parser_factory_rejects_missing_builder_in_custom_registry():
def test_parser_registry_is_immutable_and_extensible():
registry = ParserRegistry()
extended = registry.register_builder(ParserKind.JSON, lambda config, **_: "x")
extended = registry.register_builder(
ParserKind.JSON, lambda config, **_: JsonMessageParser()
)
assert registry.supported_kinds() == ()
assert extended.supported_kinds() == (ParserKind.JSON,)

View File

@ -7,12 +7,12 @@ from dataclasses import dataclass
import pytest
from app.adapters.skeleton.acquisition import PollingReadStrategy
from app.adapters.skeleton.base import BaseAcquisitionStrategy
from app.adapters.skeleton.base import BaseAcquisitionStrategy, BaseConnectionDriver
from app.adapters.skeleton.model import RawMessage
@dataclass
class FakePollingDriver:
class FakePollingDriver(BaseConnectionDriver[RawMessage]):
inbox: list[RawMessage]
connected: bool = True
receives: int = 0

View File

@ -139,14 +139,14 @@ def test_universal_adapter_runtime_processes_messages_end_to_end(
export_port = RecordingExportPort()
runtime = UniversalAdapterRuntime(
config=runtime_config,
connection_factory=lambda config: driver,
acquisition_factory=lambda connection, acquisition: PollingReadStrategy(
connection_factory=lambda config, **kwargs: driver,
acquisition_factory=lambda connection, acquisition, **kwargs: PollingReadStrategy(
interval_seconds=0.0,
initial_delay_seconds=0.0,
run_immediately=True,
sleeper=lambda _: None,
),
parser_factory=lambda config: JsonMessageParser(),
parser_factory=lambda config, **kwargs: JsonMessageParser(),
export_port=export_port,
observability=observability,
)
@ -188,14 +188,14 @@ def test_universal_adapter_runtime_isolates_parse_errors(
export_port = RecordingExportPort()
runtime = UniversalAdapterRuntime(
config=runtime_config,
connection_factory=lambda config: driver,
acquisition_factory=lambda connection, acquisition: PollingReadStrategy(
connection_factory=lambda config, **kwargs: driver,
acquisition_factory=lambda connection, acquisition, **kwargs: PollingReadStrategy(
interval_seconds=0.0,
initial_delay_seconds=0.0,
run_immediately=True,
sleeper=lambda _: None,
),
parser_factory=lambda config: FailingJsonParser(),
parser_factory=lambda config, **kwargs: FailingJsonParser(),
export_port=export_port,
observability=observability,
)
@ -219,14 +219,14 @@ def test_universal_adapter_runtime_marks_failed_on_terminal_connection_failure(
driver = RecordingConnectionDriver([], fail_connects=1)
runtime = UniversalAdapterRuntime(
config=runtime_config,
connection_factory=lambda config: driver,
acquisition_factory=lambda connection, acquisition: PollingReadStrategy(
connection_factory=lambda config, **kwargs: driver,
acquisition_factory=lambda connection, acquisition, **kwargs: PollingReadStrategy(
interval_seconds=0.0,
initial_delay_seconds=0.0,
run_immediately=True,
sleeper=lambda _: None,
),
parser_factory=lambda config: JsonMessageParser(),
parser_factory=lambda config, **kwargs: JsonMessageParser(),
export_port=RecordingExportPort(),
observability=observability,
reconnect_policy=ReconnectPolicy(max_attempts=0, initial_delay_seconds=0.1),

View File

@ -3,6 +3,7 @@
from __future__ import annotations
from io import BytesIO
from typing import Any, cast
from app.adapters.skeleton.model import CanonicalMessage, Envelope, Payload
from app.director.stdout_proto import (
@ -34,8 +35,8 @@ def test_stdout_proto_director_writes_length_delimited_frames() -> None:
frames = read_framed_messages(BytesIO(stream.getvalue()))
assert len(frames) == 2
decoded = wire.CanonicalMessage()
decoded = cast(Any, wire.CanonicalMessage())
decoded.ParseFromString(frames[0])
assert decoded.envelope.source == "source-1"
assert decoded.payload.WhichOneof("kind") == "json_value"
assert decoded.meta["adapter"] == "file"
assert decoded.meta["adapter"] == "file"

View File

@ -18,10 +18,10 @@ from app.adapters.skeleton.connection import (
)
from app.adapters.skeleton.model import RawMessage
AF_UNIX = getattr(socket, "AF_UNIX", None)
pytestmark = pytest.mark.skipif(
not hasattr(socket, "AF_UNIX"), reason="AF_UNIX sockets are unavailable"
AF_UNIX is None, reason="AF_UNIX sockets are unavailable"
)
DATA_ROOT = Path(__file__).resolve().parents[1] / ".tmp" / "unix_socket_driver"
@ -38,7 +38,8 @@ class UnixSocketFixture:
self.path.parent.mkdir(parents=True, exist_ok=True)
if self.path.exists():
self.path.unlink()
self.server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
assert AF_UNIX is not None
self.server_socket = socket.socket(AF_UNIX, socket.SOCK_STREAM)
self.server_socket.bind(str(self.path))
self.server_socket.listen(1)
self.thread = threading.Thread(