merge: feat/dispatch-alignment — dispatch client envelope profile + endpoint fix
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,7 @@ Design notes:
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@@ -40,6 +41,16 @@ def deterministic_event_id(*parts: Any) -> str:
|
|||||||
return str(uuid.uuid5(_DISPATCH_NAMESPACE, ":".join(str(p) for p in parts)))
|
return str(uuid.uuid5(_DISPATCH_NAMESPACE, ":".join(str(p) for p in parts)))
|
||||||
|
|
||||||
|
|
||||||
|
def _card_uid(value: str) -> str:
|
||||||
|
"""Envelope card_uid must be a UUID (dispatch_api/models.py). Business ids
|
||||||
|
that are already UUIDs pass through; ULID-style asset ids map to a stable
|
||||||
|
uuid5 so re-emits keep the same card."""
|
||||||
|
try:
|
||||||
|
return str(uuid.UUID(str(value)))
|
||||||
|
except ValueError:
|
||||||
|
return str(uuid.uuid5(_DISPATCH_NAMESPACE, str(value)))
|
||||||
|
|
||||||
|
|
||||||
def build_envelope(
|
def build_envelope(
|
||||||
message_type: str,
|
message_type: str,
|
||||||
card_uid: str,
|
card_uid: str,
|
||||||
@@ -49,15 +60,37 @@ def build_envelope(
|
|||||||
message_id: str | None = None,
|
message_id: str | None = None,
|
||||||
created_at: str | None = None,
|
created_at: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""Build the dispatch JSON envelope (INTER_MODULE_CONTRACT §2.4)."""
|
"""Build the dispatch JSON envelope (02 §2.4 + platform doc 23 profile).
|
||||||
|
|
||||||
|
The card block mirrors the mandatory DispatchCard fields of the platform
|
||||||
|
pydantic model (dispatch_api/models.py): int schema_version/state_code,
|
||||||
|
task_id 0 for out-of-ticket events, int4-safe epoch-second
|
||||||
|
sequence_number; the event payload nests under card.event untouched.
|
||||||
|
"""
|
||||||
|
now = created_at or datetime.now(tz=UTC).isoformat()
|
||||||
|
uid = _card_uid(card_uid)
|
||||||
return {
|
return {
|
||||||
"message_id": message_id or str(uuid.uuid4()),
|
"message_id": message_id or str(uuid.uuid4()),
|
||||||
"event_id": event_id or str(uuid.uuid4()),
|
"event_id": event_id or str(uuid.uuid4()),
|
||||||
"card_uid": str(card_uid),
|
"card_uid": uid,
|
||||||
|
"task_id": 0,
|
||||||
"message_type": message_type,
|
"message_type": message_type,
|
||||||
"participant_code": settings.dispatch_participant_code,
|
"participant_code": settings.dispatch_participant_code,
|
||||||
"created_at": created_at or datetime.now(tz=UTC).isoformat(),
|
"created_at": now,
|
||||||
"body": body,
|
"card": {
|
||||||
|
"schema_version": 1,
|
||||||
|
"card_uid": uid,
|
||||||
|
"task_id": 0,
|
||||||
|
"sequence_number": int(time.time()),
|
||||||
|
"created_at": now,
|
||||||
|
"updated_at": now,
|
||||||
|
"state_code": 0,
|
||||||
|
"specialist_status": "n/a",
|
||||||
|
"event": body,
|
||||||
|
},
|
||||||
|
"media_files": [],
|
||||||
|
"media_file_count": 0,
|
||||||
|
"local_delivery_status": {},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -80,7 +113,7 @@ def publish(
|
|||||||
envelope = build_envelope(message_type, card_uid, body, event_id=event_id)
|
envelope = build_envelope(message_type, card_uid, body, event_id=event_id)
|
||||||
try:
|
try:
|
||||||
res = httpx.post(
|
res = httpx.post(
|
||||||
f"{settings.dispatch_api_url.rstrip('/')}/messages",
|
f"{settings.dispatch_api_url.rstrip('/')}/dispatch/envelopes",
|
||||||
json=envelope,
|
json=envelope,
|
||||||
headers={"X-API-Key": settings.dispatch_api_key},
|
headers={"X-API-Key": settings.dispatch_api_key},
|
||||||
timeout=settings.dispatch_timeout_seconds,
|
timeout=settings.dispatch_timeout_seconds,
|
||||||
@@ -172,7 +205,10 @@ def handle_inbox_message(envelope: dict[str, Any]) -> dict[str, Any]:
|
|||||||
|
|
||||||
event_id = str(envelope.get("event_id") or "")
|
event_id = str(envelope.get("event_id") or "")
|
||||||
message_type = str(envelope.get("message_type") or "")
|
message_type = str(envelope.get("message_type") or "")
|
||||||
body = envelope.get("body") or {}
|
# Doc 23 profile nests the payload under card.event; legacy senders used a
|
||||||
|
# root-level body. Accept both at this external boundary.
|
||||||
|
card = envelope.get("card") or {}
|
||||||
|
body = card.get("event") or envelope.get("body") or {}
|
||||||
|
|
||||||
with session_scope() as db:
|
with session_scope() as db:
|
||||||
already = db.execute(
|
already = db.execute(
|
||||||
|
|||||||
@@ -11,14 +11,39 @@ from fastapi.testclient import TestClient
|
|||||||
from app.integrations import dispatch_client
|
from app.integrations import dispatch_client
|
||||||
|
|
||||||
|
|
||||||
def test_build_envelope_has_required_fields():
|
def test_build_envelope_matches_event_card_profile():
|
||||||
env = dispatch_client.build_envelope("LegacyhubDocumentIndexed", "card-1", {"x": 1}, event_id="e1")
|
env = dispatch_client.build_envelope("LegacyhubDocumentIndexed", "card-1", {"x": 1}, event_id="e1")
|
||||||
assert env["message_type"] == "LegacyhubDocumentIndexed"
|
assert env["message_type"] == "LegacyhubDocumentIndexed"
|
||||||
assert env["card_uid"] == "card-1"
|
|
||||||
assert env["event_id"] == "e1"
|
assert env["event_id"] == "e1"
|
||||||
assert env["participant_code"] == "legacyhub"
|
assert env["participant_code"] == "legacyhub"
|
||||||
assert "message_id" in env and "created_at" in env
|
assert "message_id" in env and "created_at" in env
|
||||||
assert env["body"] == {"x": 1}
|
# Doc 23 event profile against the platform pydantic model: UUID card_uid,
|
||||||
|
# int task_id/state_code/schema_version, payload under card.event.
|
||||||
|
import uuid as _uuid
|
||||||
|
|
||||||
|
_uuid.UUID(env["card_uid"]) # non-UUID business id mapped to stable uuid5
|
||||||
|
assert env["task_id"] == 0
|
||||||
|
card = env["card"]
|
||||||
|
assert card["card_uid"] == env["card_uid"]
|
||||||
|
assert card["schema_version"] == 1
|
||||||
|
assert card["task_id"] == 0
|
||||||
|
assert card["state_code"] == 0
|
||||||
|
assert card["specialist_status"] == "n/a"
|
||||||
|
assert isinstance(card["sequence_number"], int)
|
||||||
|
assert 0 < card["sequence_number"] < 2**31 # int4 column in dispatch-db
|
||||||
|
assert card["created_at"] == env["created_at"] == card["updated_at"]
|
||||||
|
assert card["event"] == {"x": 1}
|
||||||
|
assert env["media_files"] == []
|
||||||
|
assert env["media_file_count"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_uid_stable_for_non_uuid_ids():
|
||||||
|
a = dispatch_client.build_envelope("E", "asset_9", {})["card_uid"]
|
||||||
|
b = dispatch_client.build_envelope("E", "asset_9", {})["card_uid"]
|
||||||
|
c = dispatch_client.build_envelope("E", "asset_10", {})["card_uid"]
|
||||||
|
assert a == b != c
|
||||||
|
passthrough = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"
|
||||||
|
assert dispatch_client.build_envelope("E", passthrough, {})["card_uid"] == passthrough
|
||||||
|
|
||||||
|
|
||||||
def test_deterministic_event_id_is_stable_and_distinct():
|
def test_deterministic_event_id_is_stable_and_distinct():
|
||||||
@@ -60,7 +85,7 @@ def test_publish_posts_when_enabled(monkeypatch):
|
|||||||
env = dispatch_client.publish("LegacyhubDocumentIndexed", "card-1", {"x": 1}, event_id="e1")
|
env = dispatch_client.publish("LegacyhubDocumentIndexed", "card-1", {"x": 1}, event_id="e1")
|
||||||
assert env is not None
|
assert env is not None
|
||||||
assert len(fake.calls) == 1
|
assert len(fake.calls) == 1
|
||||||
assert fake.calls[0]["url"].endswith("/messages")
|
assert fake.calls[0]["url"].endswith("/dispatch/envelopes")
|
||||||
assert fake.calls[0]["headers"]["X-API-Key"] == "k"
|
assert fake.calls[0]["headers"]["X-API-Key"] == "k"
|
||||||
|
|
||||||
|
|
||||||
@@ -74,9 +99,9 @@ def test_publish_document_indexed_uses_asset_id_as_card(monkeypatch):
|
|||||||
"doc-uuid", asset_metadata={"asset_id": "asset_9", "owner_module": "qms"}
|
"doc-uuid", asset_metadata={"asset_id": "asset_9", "owner_module": "qms"}
|
||||||
)
|
)
|
||||||
assert env is not None
|
assert env is not None
|
||||||
assert env["card_uid"] == "asset_9"
|
assert env["card_uid"] == dispatch_client._card_uid("asset_9")
|
||||||
assert env["body"]["asset_id"] == "asset_9"
|
assert env["card"]["event"]["asset_id"] == "asset_9"
|
||||||
assert env["body"]["owner_module"] == "qms"
|
assert env["card"]["event"]["owner_module"] == "qms"
|
||||||
|
|
||||||
|
|
||||||
# ---- inbox route ----
|
# ---- inbox route ----
|
||||||
|
|||||||
Reference in New Issue
Block a user