Add JSON logging for command websocket
This commit is contained in:
parent
ba5ee31c15
commit
9db554ca50
|
|
@ -10,3 +10,4 @@ htmlcov/
|
|||
build/
|
||||
dist/
|
||||
*.egg-info/
|
||||
log/
|
||||
|
|
|
|||
|
|
@ -1,12 +1,15 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from time import time_ns
|
||||
from typing import Any
|
||||
|
||||
import websockets
|
||||
from google.protobuf.json_format import MessageToDict
|
||||
|
||||
from app.command.bridge.codec import CommandBridgeNorthboundCodec
|
||||
from app.command.bridge.models_websocket import (
|
||||
|
|
@ -49,6 +52,43 @@ def _body_name(envelope: Any) -> str:
|
|||
return str(which_oneof("body") or "")
|
||||
|
||||
|
||||
def _envelope_to_json_record(
|
||||
*,
|
||||
direction: str,
|
||||
transport_name: str,
|
||||
session_id: str,
|
||||
envelope: Any,
|
||||
) -> dict[str, Any]:
|
||||
record: dict[str, Any] = {
|
||||
"timestamp_unix_ms": _now_ms(),
|
||||
"transport": transport_name,
|
||||
"direction": direction,
|
||||
"session_id": session_id,
|
||||
"request_id": _request_id(envelope),
|
||||
"correlation_id": str(getattr(envelope, "correlation_id", "") or ""),
|
||||
"message_kind": _message_kind(envelope),
|
||||
"body_name": _body_name(envelope),
|
||||
}
|
||||
try:
|
||||
record["envelope"] = MessageToDict(
|
||||
envelope,
|
||||
preserving_proto_field_name=True,
|
||||
)
|
||||
except Exception:
|
||||
record["envelope"] = {"repr": str(envelope)}
|
||||
return record
|
||||
|
||||
|
||||
def _append_json_log(record: dict[str, Any]) -> None:
|
||||
log_dir = Path("log")
|
||||
log_path = log_dir / "command-websocket.jsonl"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
line = json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
with log_path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(line)
|
||||
handle.write("\n")
|
||||
|
||||
|
||||
class CommandBridgeWebSocketTransport(CommandResultPort):
|
||||
def __init__(
|
||||
self,
|
||||
|
|
@ -182,6 +222,7 @@ class CommandBridgeWebSocketTransport(CommandResultPort):
|
|||
) -> Any:
|
||||
session = self._get_session(session_id)
|
||||
envelope.session_id = session_id
|
||||
self._log_inbound_envelope(session_id, envelope)
|
||||
|
||||
request_id = _request_id(envelope)
|
||||
message_kind = _message_kind(envelope)
|
||||
|
|
@ -308,6 +349,7 @@ class CommandBridgeWebSocketTransport(CommandResultPort):
|
|||
await self._send_binary_async(
|
||||
session.websocket, envelope.SerializeToString()
|
||||
)
|
||||
self._log_outbound_envelope(session_id, envelope)
|
||||
except Exception as exc:
|
||||
with self._lock:
|
||||
self._failed_count += 1
|
||||
|
|
@ -354,6 +396,7 @@ class CommandBridgeWebSocketTransport(CommandResultPort):
|
|||
session_id=session_id,
|
||||
)
|
||||
await self._send_binary_async(websocket, response.SerializeToString())
|
||||
self._log_outbound_envelope(session_id, response)
|
||||
with self._lock:
|
||||
session = self._sessions.get(session_id)
|
||||
if session is not None:
|
||||
|
|
@ -393,6 +436,7 @@ class CommandBridgeWebSocketTransport(CommandResultPort):
|
|||
try:
|
||||
session = self._get_session(session_id)
|
||||
self._send_binary_sync(session.websocket, envelope.SerializeToString())
|
||||
self._log_outbound_envelope(session_id, envelope)
|
||||
except Exception as exc:
|
||||
with self._lock:
|
||||
self._failed_count += 1
|
||||
|
|
@ -423,3 +467,23 @@ class CommandBridgeWebSocketTransport(CommandResultPort):
|
|||
self._status = status
|
||||
if self._observability is not None:
|
||||
self._observability.set_bridge_status(status)
|
||||
|
||||
def _log_inbound_envelope(self, session_id: str, envelope: Any) -> None:
|
||||
_append_json_log(
|
||||
_envelope_to_json_record(
|
||||
direction="inbound",
|
||||
transport_name=self.name,
|
||||
session_id=session_id,
|
||||
envelope=envelope,
|
||||
)
|
||||
)
|
||||
|
||||
def _log_outbound_envelope(self, session_id: str, envelope: Any) -> None:
|
||||
_append_json_log(
|
||||
_envelope_to_json_record(
|
||||
direction="outbound",
|
||||
transport_name=self.name,
|
||||
session_id=session_id,
|
||||
envelope=envelope,
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from app.command import (
|
||||
CommandBridge,
|
||||
|
|
@ -208,3 +210,50 @@ def test_command_websocket_transport_returns_protocol_errors() -> None:
|
|||
assert envelope.message_kind == "ERROR"
|
||||
assert envelope.error.error_code == CommandErrorCode.VALIDATION_FAILED.value
|
||||
assert transport.status().failed_count == 0
|
||||
|
||||
|
||||
def test_command_websocket_transport_logs_json_messages_to_log_dir(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
codec = CommandBridgeNorthboundCodec(server_name="wf-agent", server_version="1")
|
||||
bridge = CommandBridge(codec=codec)
|
||||
transport = CommandBridgeWebSocketTransport(bridge=bridge)
|
||||
bridge.register_transport(transport)
|
||||
|
||||
websocket = FakeWebSocket()
|
||||
session_id = transport.register_session(websocket, "session-json")
|
||||
|
||||
hello = codec.build_client_hello(
|
||||
client_type="cli",
|
||||
client_version="0.1.0",
|
||||
session_id=session_id,
|
||||
request_id="hello-json-1",
|
||||
correlation_id="corr-json-1",
|
||||
)
|
||||
asyncio.run(transport.process_client_envelope(session_id, hello))
|
||||
|
||||
log_path = tmp_path / "log" / "command-websocket.jsonl"
|
||||
assert log_path.exists()
|
||||
|
||||
records = [
|
||||
json.loads(line)
|
||||
for line in log_path.read_text(encoding="utf-8").splitlines()
|
||||
if line.strip()
|
||||
]
|
||||
assert len(records) == 2
|
||||
|
||||
inbound, outbound = records
|
||||
assert inbound["direction"] == "inbound"
|
||||
assert inbound["transport"] == transport.name
|
||||
assert inbound["session_id"] == session_id
|
||||
assert inbound["message_kind"] == "CLIENT_HELLO"
|
||||
assert inbound["envelope"]["client_hello"]["client_type"] == "cli"
|
||||
|
||||
assert outbound["direction"] == "outbound"
|
||||
assert outbound["transport"] == transport.name
|
||||
assert outbound["session_id"] == session_id
|
||||
assert outbound["message_kind"] == "SERVER_HELLO"
|
||||
assert outbound["envelope"]["server_hello"]["server_name"] == "wf-agent"
|
||||
|
|
|
|||
Loading…
Reference in New Issue