sontris-interceptor 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sontris/__init__.py +1 -0
- sontris/testing/__init__.py +1 -0
- sontris/testing/interceptor/__init__.py +15 -0
- sontris/testing/interceptor/capture/__init__.py +1 -0
- sontris/testing/interceptor/capture/jsonl.py +63 -0
- sontris/testing/interceptor/core/__init__.py +1 -0
- sontris/testing/interceptor/core/config.py +114 -0
- sontris/testing/interceptor/core/exceptions.py +17 -0
- sontris/testing/interceptor/core/message.py +32 -0
- sontris/testing/interceptor/core/registry.py +100 -0
- sontris/testing/interceptor/interceptor.py +227 -0
- sontris/testing/interceptor/processing/__init__.py +1 -0
- sontris/testing/interceptor/processing/pipeline.py +133 -0
- sontris/testing/interceptor/protocols/__init__.py +1 -0
- sontris/testing/interceptor/protocols/base.py +34 -0
- sontris/testing/interceptor/protocols/pubsub/__init__.py +1 -0
- sontris/testing/interceptor/protocols/pubsub/adapter.py +165 -0
- sontris/testing/interceptor/transports/__init__.py +1 -0
- sontris/testing/interceptor/transports/base.py +12 -0
- sontris/testing/interceptor/transports/tcp.py +29 -0
- sontris_interceptor-0.0.1.dist-info/METADATA +102 -0
- sontris_interceptor-0.0.1.dist-info/RECORD +25 -0
- sontris_interceptor-0.0.1.dist-info/WHEEL +4 -0
- sontris_interceptor-0.0.1.dist-info/entry_points.txt +2 -0
- sontris_interceptor-0.0.1.dist-info/licenses/LICENSE +304 -0
sontris/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Sontris packages."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Sontris testing packages."""
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Public package API for the NNG interceptor."""
|
|
2
|
+
|
|
3
|
+
from sontris.testing.interceptor.interceptor import NNGInterceptor
|
|
4
|
+
|
|
5
|
+
__all__: list[str] = ["NNGInterceptor", "main"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main() -> None:
|
|
9
|
+
"""Print package usage information.
|
|
10
|
+
|
|
11
|
+
Example:
|
|
12
|
+
>>> main()
|
|
13
|
+
sontris-interceptor
|
|
14
|
+
"""
|
|
15
|
+
print("sontris-interceptor")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Capture modules."""
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""JSON Lines capture recorder."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import threading
|
|
6
|
+
from _thread import LockType
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, TextIO
|
|
9
|
+
|
|
10
|
+
from sontris.testing.interceptor.core.message import InterceptedMessage
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class JsonlRecorder:
|
|
14
|
+
"""Capture intercepted messages to JSONL without blocking forwarding."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, path: str | Path) -> None:
|
|
17
|
+
"""Initialize a recorder.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
path: JSONL output path.
|
|
21
|
+
"""
|
|
22
|
+
self.path: Path = Path(path)
|
|
23
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
self._lock: LockType = threading.Lock()
|
|
25
|
+
|
|
26
|
+
def record(self, message: InterceptedMessage) -> None:
|
|
27
|
+
"""Append a message to the JSONL file.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
message: Message to record.
|
|
31
|
+
|
|
32
|
+
Example:
|
|
33
|
+
>>> import tempfile
|
|
34
|
+
>>> from pathlib import Path
|
|
35
|
+
>>> with tempfile.TemporaryDirectory() as directory:
|
|
36
|
+
... recorder = JsonlRecorder(Path(directory) / "capture.jsonl")
|
|
37
|
+
... recorder.record(InterceptedMessage(payload=b"hello"))
|
|
38
|
+
"""
|
|
39
|
+
record: dict[str, Any] = {
|
|
40
|
+
"message_id": message.message_id,
|
|
41
|
+
"timestamp": message.timestamp,
|
|
42
|
+
"protocol": message.protocol,
|
|
43
|
+
"transport": message.transport,
|
|
44
|
+
"source": message.source,
|
|
45
|
+
"destination": message.destination,
|
|
46
|
+
"direction": message.direction,
|
|
47
|
+
"payload_base64": base64.b64encode(message.payload).decode("ascii"),
|
|
48
|
+
"original_payload_base64": (
|
|
49
|
+
None
|
|
50
|
+
if message.original_payload is None
|
|
51
|
+
else base64.b64encode(message.original_payload).decode("ascii")
|
|
52
|
+
),
|
|
53
|
+
"metadata": message.metadata,
|
|
54
|
+
"manipulated": message.manipulated,
|
|
55
|
+
"injection": message.injection,
|
|
56
|
+
"processing_status": message.processing_status,
|
|
57
|
+
"action": message.action,
|
|
58
|
+
}
|
|
59
|
+
line: str = json.dumps(record, ensure_ascii=False)
|
|
60
|
+
handle: TextIO
|
|
61
|
+
with self._lock:
|
|
62
|
+
with self.path.open("a", encoding="utf-8") as handle:
|
|
63
|
+
handle.write(line + "\n")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core abstractions for the interceptor framework."""
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Configuration loading and validation."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import yaml
|
|
7
|
+
|
|
8
|
+
from sontris.testing.interceptor.core.exceptions import ConfigurationError
|
|
9
|
+
|
|
10
|
+
_TOP_LEVEL_KEYS: set[str] = {"framework", "system", "interceptor"}
|
|
11
|
+
_INTERCEPTOR_KEYS: set[str] = {
|
|
12
|
+
"protocol",
|
|
13
|
+
"transport",
|
|
14
|
+
"mode",
|
|
15
|
+
"endpoints",
|
|
16
|
+
"socket_options",
|
|
17
|
+
"capture",
|
|
18
|
+
"processing",
|
|
19
|
+
"injection",
|
|
20
|
+
"timeouts",
|
|
21
|
+
}
|
|
22
|
+
_ENDPOINT_KEYS: set[str] = {"listen", "target"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def load_config(path: str | Path) -> dict[str, Any]:
|
|
26
|
+
"""Load and validate a YAML interceptor configuration.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
path: Path to the YAML configuration file.
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
A validated configuration dictionary.
|
|
33
|
+
|
|
34
|
+
Raises:
|
|
35
|
+
ConfigurationError: If YAML or required configuration is invalid.
|
|
36
|
+
|
|
37
|
+
Example:
|
|
38
|
+
>>> # Load a real configuration with load_config("config.yaml")
|
|
39
|
+
"""
|
|
40
|
+
config_path: Path = Path(path)
|
|
41
|
+
data: Any
|
|
42
|
+
exc: Exception
|
|
43
|
+
try:
|
|
44
|
+
data = yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
|
45
|
+
except yaml.YAMLError as exc:
|
|
46
|
+
raise ConfigurationError(f"Invalid YAML in {config_path}: {exc}") from exc
|
|
47
|
+
except OSError as exc:
|
|
48
|
+
raise ConfigurationError(
|
|
49
|
+
f"Cannot read configuration {config_path}: {exc}"
|
|
50
|
+
) from exc
|
|
51
|
+
if not isinstance(data, dict):
|
|
52
|
+
raise ConfigurationError("Configuration root must be a mapping")
|
|
53
|
+
unknown: set[Any] = set(data) - _TOP_LEVEL_KEYS
|
|
54
|
+
if unknown:
|
|
55
|
+
raise ConfigurationError(f"Unknown top-level keys: {sorted(unknown)}")
|
|
56
|
+
validate_config(data)
|
|
57
|
+
return data
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def validate_config(config: dict[str, Any]) -> dict[str, Any]:
|
|
61
|
+
"""Validate the framework and interceptor sections.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
config: Configuration mapping to validate.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
The original mapping.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
ConfigurationError: If required or unknown fields are invalid.
|
|
71
|
+
|
|
72
|
+
Example:
|
|
73
|
+
>>> config = {"interceptor": {"protocol": "pubsub", "transport": "tcp",
|
|
74
|
+
... "endpoints": {"listen": "tcp://127.0.0.1:5555",
|
|
75
|
+
... "target": "tcp://127.0.0.1:5556"}}}
|
|
76
|
+
>>> validate_config(config)["interceptor"]["protocol"]
|
|
77
|
+
'pubsub'
|
|
78
|
+
"""
|
|
79
|
+
interceptor: Any = config.get("interceptor")
|
|
80
|
+
if not isinstance(interceptor, dict):
|
|
81
|
+
raise ConfigurationError("Missing interceptor mapping")
|
|
82
|
+
unknown: set[Any] = set(interceptor) - _INTERCEPTOR_KEYS
|
|
83
|
+
if unknown:
|
|
84
|
+
raise ConfigurationError(f"Unknown interceptor keys: {sorted(unknown)}")
|
|
85
|
+
protocol: Any = interceptor.get("protocol")
|
|
86
|
+
transport: Any = interceptor.get("transport")
|
|
87
|
+
if protocol != "pubsub":
|
|
88
|
+
raise ConfigurationError(
|
|
89
|
+
f"Unsupported protocol module '{protocol}'; only 'pubsub' is implemented"
|
|
90
|
+
)
|
|
91
|
+
if transport != "tcp":
|
|
92
|
+
raise ConfigurationError(
|
|
93
|
+
f"Unsupported transport module '{transport}'; only 'tcp' is implemented"
|
|
94
|
+
)
|
|
95
|
+
endpoints: Any = interceptor.get("endpoints")
|
|
96
|
+
if not isinstance(endpoints, dict):
|
|
97
|
+
raise ConfigurationError("Missing interceptor.endpoints mapping")
|
|
98
|
+
unknown_endpoints: set[Any] = set(endpoints) - _ENDPOINT_KEYS
|
|
99
|
+
if unknown_endpoints:
|
|
100
|
+
raise ConfigurationError(
|
|
101
|
+
f"Unknown interceptor.endpoints keys: {sorted(unknown_endpoints)}"
|
|
102
|
+
)
|
|
103
|
+
listen: Any = endpoints.get("listen")
|
|
104
|
+
target: Any = endpoints.get("target")
|
|
105
|
+
if not isinstance(listen, str) or not listen.startswith("tcp://"):
|
|
106
|
+
raise ConfigurationError("interceptor.endpoints.listen must be a TCP URL")
|
|
107
|
+
if not isinstance(target, str) or not target.startswith("tcp://"):
|
|
108
|
+
raise ConfigurationError("interceptor.endpoints.target must be a TCP URL")
|
|
109
|
+
mode: Any = interceptor.get("mode", "interception")
|
|
110
|
+
if mode not in {"interception", "simulation"}:
|
|
111
|
+
raise ConfigurationError("interceptor.mode must be interception or simulation")
|
|
112
|
+
if mode == "simulation":
|
|
113
|
+
raise ConfigurationError("PUB/SUB component simulation is not implemented")
|
|
114
|
+
return config
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Framework-specific exceptions."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class InterceptorError(Exception):
|
|
5
|
+
"""Base exception for interceptor failures."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ConfigurationError(InterceptorError):
|
|
9
|
+
"""Raised when an interceptor configuration is invalid."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ModuleNotFoundError(InterceptorError):
|
|
13
|
+
"""Raised when a protocol or transport module is unavailable."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UnsupportedActionError(InterceptorError):
|
|
17
|
+
"""Raised when a protocol does not support a processing action."""
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Internal intercepted-message representation."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import UTC, datetime
|
|
5
|
+
from typing import Any
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(slots=True)
|
|
10
|
+
class InterceptedMessage:
|
|
11
|
+
"""Describe a payload while preserving its original bytes.
|
|
12
|
+
|
|
13
|
+
Example:
|
|
14
|
+
>>> message = InterceptedMessage(payload=b"hello")
|
|
15
|
+
>>> message.payload
|
|
16
|
+
b'hello'
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
payload: bytes
|
|
20
|
+
protocol: str = ""
|
|
21
|
+
transport: str = ""
|
|
22
|
+
source: str | None = None
|
|
23
|
+
destination: str | None = None
|
|
24
|
+
direction: str = "input"
|
|
25
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
26
|
+
message_id: str = field(default_factory=lambda: str(uuid4()))
|
|
27
|
+
timestamp: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
|
|
28
|
+
original_payload: bytes | None = None
|
|
29
|
+
manipulated: bool = False
|
|
30
|
+
injection: bool = False
|
|
31
|
+
processing_status: str = "received"
|
|
32
|
+
action: str = "PASS"
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Registries for protocol and transport modules."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Any, TypeAlias
|
|
5
|
+
|
|
6
|
+
from sontris.testing.interceptor.core.exceptions import ModuleNotFoundError
|
|
7
|
+
|
|
8
|
+
ProtocolFactory: TypeAlias = Callable[[dict[str, Any]], object]
|
|
9
|
+
TransportFactory: TypeAlias = Callable[[dict[str, Any]], object]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ModuleRegistry:
|
|
13
|
+
"""Resolve configured protocol and transport modules."""
|
|
14
|
+
|
|
15
|
+
def __init__(self) -> None:
|
|
16
|
+
"""Initialize empty protocol and transport registries."""
|
|
17
|
+
self._protocols: dict[str, ProtocolFactory] = {}
|
|
18
|
+
self._transports: dict[str, TransportFactory] = {}
|
|
19
|
+
|
|
20
|
+
def register_protocol(self, name: str, factory: ProtocolFactory) -> None:
|
|
21
|
+
"""Register a protocol factory.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
name: Protocol identifier.
|
|
25
|
+
factory: Factory accepting configuration.
|
|
26
|
+
|
|
27
|
+
Example:
|
|
28
|
+
>>> registry = ModuleRegistry()
|
|
29
|
+
>>> registry.register_protocol("example", lambda config: object())
|
|
30
|
+
"""
|
|
31
|
+
self._protocols[name] = factory
|
|
32
|
+
|
|
33
|
+
def register_transport(self, name: str, factory: TransportFactory) -> None:
|
|
34
|
+
"""Register a transport factory.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
name: Transport identifier.
|
|
38
|
+
factory: Factory accepting configuration.
|
|
39
|
+
|
|
40
|
+
Example:
|
|
41
|
+
>>> registry = ModuleRegistry()
|
|
42
|
+
>>> registry.register_transport("tcp", lambda config: object())
|
|
43
|
+
"""
|
|
44
|
+
self._transports[name] = factory
|
|
45
|
+
|
|
46
|
+
def create_protocol(
|
|
47
|
+
self,
|
|
48
|
+
name: str,
|
|
49
|
+
config: dict[str, Any],
|
|
50
|
+
) -> object:
|
|
51
|
+
"""Create a protocol module.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
name: Protocol identifier.
|
|
55
|
+
config: Protocol configuration.
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
The created protocol module.
|
|
59
|
+
|
|
60
|
+
Raises:
|
|
61
|
+
ModuleNotFoundError: If the protocol is not registered.
|
|
62
|
+
|
|
63
|
+
Example:
|
|
64
|
+
>>> registry = ModuleRegistry()
|
|
65
|
+
>>> registry.create_protocol("missing", {})
|
|
66
|
+
Traceback (most recent call last):
|
|
67
|
+
...
|
|
68
|
+
"""
|
|
69
|
+
factory: ProtocolFactory | None = self._protocols.get(name)
|
|
70
|
+
if factory is None:
|
|
71
|
+
raise ModuleNotFoundError(f"No protocol module registered for '{name}'")
|
|
72
|
+
return factory(config)
|
|
73
|
+
|
|
74
|
+
def create_transport(
|
|
75
|
+
self,
|
|
76
|
+
name: str,
|
|
77
|
+
config: dict[str, Any],
|
|
78
|
+
) -> object:
|
|
79
|
+
"""Create a transport module.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
name: Transport identifier.
|
|
83
|
+
config: Transport configuration.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
The created transport module.
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
ModuleNotFoundError: If the transport is not registered.
|
|
90
|
+
|
|
91
|
+
Example:
|
|
92
|
+
>>> registry = ModuleRegistry()
|
|
93
|
+
>>> registry.create_transport("missing", {})
|
|
94
|
+
Traceback (most recent call last):
|
|
95
|
+
...
|
|
96
|
+
"""
|
|
97
|
+
factory: TransportFactory | None = self._transports.get(name)
|
|
98
|
+
if factory is None:
|
|
99
|
+
raise ModuleNotFoundError(f"No transport module registered for '{name}'")
|
|
100
|
+
return factory(config)
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Public interceptor lifecycle API."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from sontris.testing.interceptor.capture.jsonl import JsonlRecorder
|
|
7
|
+
from sontris.testing.interceptor.core.config import load_config, validate_config
|
|
8
|
+
from sontris.testing.interceptor.core.message import InterceptedMessage
|
|
9
|
+
from sontris.testing.interceptor.core.registry import ModuleRegistry
|
|
10
|
+
from sontris.testing.interceptor.processing.pipeline import ProcessingPipeline
|
|
11
|
+
from sontris.testing.interceptor.protocols.base import ProtocolAdapter
|
|
12
|
+
from sontris.testing.interceptor.protocols.pubsub.adapter import PubSubAdapter
|
|
13
|
+
from sontris.testing.interceptor.transports.base import TransportAdapter
|
|
14
|
+
from sontris.testing.interceptor.transports.tcp import TcpTransport
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class NNGInterceptor:
|
|
18
|
+
"""Configure, start, stop, and operate a NNG cooked-mode interceptor.
|
|
19
|
+
|
|
20
|
+
Example:
|
|
21
|
+
>>> interceptor = NNGInterceptor({
|
|
22
|
+
... "interceptor": {
|
|
23
|
+
... "protocol": "pubsub",
|
|
24
|
+
... "transport": "tcp",
|
|
25
|
+
... "endpoints": {
|
|
26
|
+
... "listen": "tcp://127.0.0.1:5555",
|
|
27
|
+
... "target": "tcp://127.0.0.1:5556",
|
|
28
|
+
... },
|
|
29
|
+
... }
|
|
30
|
+
... })
|
|
31
|
+
>>> interceptor.get_status()["initialized"]
|
|
32
|
+
False
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
config: dict[str, Any] | str | Path | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""Initialize the interceptor from a mapping or YAML path.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
config: Configuration mapping or YAML path.
|
|
43
|
+
"""
|
|
44
|
+
if config is None:
|
|
45
|
+
raise ValueError("A configuration mapping or path is required")
|
|
46
|
+
loaded: dict[str, Any]
|
|
47
|
+
if isinstance(config, (str, Path)):
|
|
48
|
+
loaded = load_config(config)
|
|
49
|
+
else:
|
|
50
|
+
loaded = config
|
|
51
|
+
validate_config(loaded)
|
|
52
|
+
self.config: dict[str, Any] = loaded
|
|
53
|
+
self._messages: list[InterceptedMessage] = []
|
|
54
|
+
self._capture_enabled: bool = bool(
|
|
55
|
+
self.config["interceptor"].get("capture", {}).get("enabled", False)
|
|
56
|
+
)
|
|
57
|
+
capture_config: Any = self.config["interceptor"].get("capture", {})
|
|
58
|
+
capture_path: Any = (
|
|
59
|
+
capture_config.get("path", "capture/messages.jsonl")
|
|
60
|
+
if isinstance(capture_config, dict)
|
|
61
|
+
else "capture/messages.jsonl"
|
|
62
|
+
)
|
|
63
|
+
self._recorder: JsonlRecorder | None = (
|
|
64
|
+
JsonlRecorder(capture_path) if self._capture_enabled else None
|
|
65
|
+
)
|
|
66
|
+
self._pipeline: ProcessingPipeline = ProcessingPipeline(
|
|
67
|
+
self.config, self._capture_message
|
|
68
|
+
)
|
|
69
|
+
self._registry: ModuleRegistry = ModuleRegistry()
|
|
70
|
+
|
|
71
|
+
def create_transport(values: dict[str, Any]) -> TcpTransport:
|
|
72
|
+
"""Create the configured TCP transport."""
|
|
73
|
+
del values
|
|
74
|
+
return TcpTransport()
|
|
75
|
+
|
|
76
|
+
def create_protocol(values: dict[str, Any]) -> PubSubAdapter:
|
|
77
|
+
"""Create the configured PUB/SUB adapter."""
|
|
78
|
+
return PubSubAdapter(values, self._pipeline.process)
|
|
79
|
+
|
|
80
|
+
self._registry.register_transport("tcp", create_transport)
|
|
81
|
+
self._registry.register_protocol(
|
|
82
|
+
"pubsub",
|
|
83
|
+
create_protocol,
|
|
84
|
+
)
|
|
85
|
+
transport_name: Any = self.config["interceptor"]["transport"]
|
|
86
|
+
transport: object = self._registry.create_transport(
|
|
87
|
+
transport_name, self.config
|
|
88
|
+
)
|
|
89
|
+
assert isinstance(transport, TransportAdapter)
|
|
90
|
+
transport.validate(self.config["interceptor"]["endpoints"])
|
|
91
|
+
protocol_name: Any = self.config["interceptor"]["protocol"]
|
|
92
|
+
protocol: object = self._registry.create_protocol(protocol_name, self.config)
|
|
93
|
+
assert isinstance(protocol, ProtocolAdapter)
|
|
94
|
+
self._protocol: ProtocolAdapter = protocol
|
|
95
|
+
self._initialized: bool = False
|
|
96
|
+
|
|
97
|
+
def start(self) -> None:
|
|
98
|
+
"""Initialize and start the interceptor."""
|
|
99
|
+
self._protocol.initialize()
|
|
100
|
+
self._protocol.start()
|
|
101
|
+
self._initialized = True
|
|
102
|
+
|
|
103
|
+
def stop(self) -> None:
|
|
104
|
+
"""Stop the interceptor and close protocol sockets."""
|
|
105
|
+
self._protocol.stop()
|
|
106
|
+
self._initialized = False
|
|
107
|
+
|
|
108
|
+
def enable_capture(self, path: str | Path | None = None) -> None:
|
|
109
|
+
"""Enable in-memory capture and optional JSONL recording.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
path: Optional JSONL destination.
|
|
113
|
+
"""
|
|
114
|
+
self._capture_enabled = True
|
|
115
|
+
if path is not None:
|
|
116
|
+
self._recorder = JsonlRecorder(path)
|
|
117
|
+
|
|
118
|
+
def disable_capture(self) -> None:
|
|
119
|
+
"""Disable JSONL recording while preserving in-memory messages."""
|
|
120
|
+
self._capture_enabled = False
|
|
121
|
+
|
|
122
|
+
def inject(self, payload: bytes | str) -> InterceptedMessage:
|
|
123
|
+
"""Inject a payload downstream.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
payload: Text or binary payload to publish.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
The injected message record.
|
|
130
|
+
|
|
131
|
+
Raises:
|
|
132
|
+
RuntimeError: If the interceptor is not started.
|
|
133
|
+
"""
|
|
134
|
+
payload_bytes: bytes = (
|
|
135
|
+
payload if isinstance(payload, bytes) else payload.encode("utf-8")
|
|
136
|
+
)
|
|
137
|
+
message: InterceptedMessage = InterceptedMessage(
|
|
138
|
+
payload=payload_bytes,
|
|
139
|
+
protocol="pubsub",
|
|
140
|
+
transport="tcp",
|
|
141
|
+
direction="output",
|
|
142
|
+
injection=True,
|
|
143
|
+
original_payload=payload_bytes,
|
|
144
|
+
processing_status="forward",
|
|
145
|
+
action="INJECT",
|
|
146
|
+
)
|
|
147
|
+
self._capture_message(message)
|
|
148
|
+
self._protocol.send(payload_bytes, {"injection": True})
|
|
149
|
+
message.processing_status = "forwarded"
|
|
150
|
+
return message
|
|
151
|
+
|
|
152
|
+
def drop(self) -> None:
|
|
153
|
+
"""Add a rule that drops all subsequent upstream messages."""
|
|
154
|
+
self._pipeline.rules.insert(0, {"action": "DROP"})
|
|
155
|
+
|
|
156
|
+
def replace(self, payload: bytes | str) -> None:
|
|
157
|
+
"""Add a rule that replaces all subsequent upstream payloads.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
payload: Replacement text or binary payload.
|
|
161
|
+
"""
|
|
162
|
+
replacement: bytes = (
|
|
163
|
+
payload if isinstance(payload, bytes) else payload.encode("utf-8")
|
|
164
|
+
)
|
|
165
|
+
self._pipeline.rules.insert(0, {"action": "REPLACE", "payload": replacement})
|
|
166
|
+
|
|
167
|
+
def add_rule(self, rule: dict[str, Any]) -> None:
|
|
168
|
+
"""Append a processing rule.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
rule: Mapping containing an action and optional payload.
|
|
172
|
+
"""
|
|
173
|
+
self._pipeline.rules.append(rule)
|
|
174
|
+
|
|
175
|
+
def clear_rules(self) -> None:
|
|
176
|
+
"""Remove all configured processing rules."""
|
|
177
|
+
self._pipeline.rules.clear()
|
|
178
|
+
|
|
179
|
+
def remove_rule(self, index: int) -> None:
|
|
180
|
+
"""Remove a processing rule by index.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
index: Zero-based rule index.
|
|
184
|
+
|
|
185
|
+
Raises:
|
|
186
|
+
IndexError: If the index is out of range.
|
|
187
|
+
"""
|
|
188
|
+
del self._pipeline.rules[index]
|
|
189
|
+
|
|
190
|
+
def get_messages(self) -> list[InterceptedMessage]:
|
|
191
|
+
"""Return captured message snapshots."""
|
|
192
|
+
return list(self._messages)
|
|
193
|
+
|
|
194
|
+
def get_statistics(self) -> dict[str, int]:
|
|
195
|
+
"""Return basic capture and processing statistics."""
|
|
196
|
+
forwarded: int = 0
|
|
197
|
+
dropped: int = 0
|
|
198
|
+
injected: int = 0
|
|
199
|
+
message: InterceptedMessage
|
|
200
|
+
for message in self._messages:
|
|
201
|
+
if message.processing_status in {"forward", "forwarded"}:
|
|
202
|
+
forwarded += 1
|
|
203
|
+
if message.processing_status == "dropped":
|
|
204
|
+
dropped += 1
|
|
205
|
+
if message.injection:
|
|
206
|
+
injected += 1
|
|
207
|
+
return {
|
|
208
|
+
"messages": len(self._messages),
|
|
209
|
+
"captured": len(self._messages),
|
|
210
|
+
"forwarded": forwarded,
|
|
211
|
+
"dropped": dropped,
|
|
212
|
+
"injected": injected,
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
def get_status(self) -> dict[str, Any]:
|
|
216
|
+
"""Return lifecycle and protocol status."""
|
|
217
|
+
status: dict[str, Any] = self._protocol.get_status()
|
|
218
|
+
status["initialized"] = self._initialized
|
|
219
|
+
status["capture_enabled"] = self._capture_enabled
|
|
220
|
+
status["message_count"] = len(self._messages)
|
|
221
|
+
return status
|
|
222
|
+
|
|
223
|
+
def _capture_message(self, message: InterceptedMessage) -> None:
|
|
224
|
+
"""Store and optionally record a message."""
|
|
225
|
+
self._messages.append(message)
|
|
226
|
+
if self._capture_enabled and self._recorder is not None:
|
|
227
|
+
self._recorder.record(message)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Message processing components."""
|