|
| 1 | +"""Contracts validate client (M2 wiring). |
| 2 | +
|
| 3 | +Wraps ``POST /api/v1/contracts/validate`` so producers can dry-run a |
| 4 | +contract before applying it. Stateless: each call is self-contained. |
| 5 | +
|
| 6 | +Example: |
| 7 | + client = ContractsClient("http://localhost:9094") |
| 8 | + result = await client.validate( |
| 9 | + contract={ |
| 10 | + "name": "orders.v1", |
| 11 | + "schema_id": 7, |
| 12 | + "fields": [{"name": "id", "type": "string", "required": True}], |
| 13 | + }, |
| 14 | + value={"id": "abc"}, |
| 15 | + ) |
| 16 | + if not result.valid: |
| 17 | + print(result.errors) |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import asyncio |
| 23 | +import json |
| 24 | +from dataclasses import dataclass, field |
| 25 | +from typing import Any, Optional, Union |
| 26 | + |
| 27 | +try: |
| 28 | + import aiohttp |
| 29 | + |
| 30 | + _HAS_AIOHTTP = True |
| 31 | +except ImportError: # pragma: no cover |
| 32 | + _HAS_AIOHTTP = False |
| 33 | + |
| 34 | +from .exceptions import StreamlineError |
| 35 | + |
| 36 | + |
| 37 | +class ContractsError(StreamlineError): |
| 38 | + """Raised when the contracts API itself fails (5xx, network, etc.).""" |
| 39 | + |
| 40 | + |
| 41 | +@dataclass |
| 42 | +class ValidationError: |
| 43 | + """A single validation failure.""" |
| 44 | + |
| 45 | + field_path: str |
| 46 | + expected: str |
| 47 | + actual: str |
| 48 | + message: str = "" |
| 49 | + |
| 50 | + @classmethod |
| 51 | + def from_json(cls, data: dict[str, Any]) -> "ValidationError": |
| 52 | + return cls( |
| 53 | + field_path=str(data.get("field_path", "")), |
| 54 | + expected=str(data.get("expected", "")), |
| 55 | + actual=str(data.get("actual", "")), |
| 56 | + message=str(data.get("message", "")), |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +@dataclass |
| 61 | +class ValidationResult: |
| 62 | + """Outcome of a contract validation request.""" |
| 63 | + |
| 64 | + valid: bool |
| 65 | + schema_id: Optional[int] = None |
| 66 | + errors: list[ValidationError] = field(default_factory=list) |
| 67 | + |
| 68 | + |
| 69 | +class ContractsClient: |
| 70 | + """Async client for the contracts validate endpoint. |
| 71 | +
|
| 72 | + Args: |
| 73 | + http_url: HTTP base URL (default: ``http://localhost:9094``). |
| 74 | + timeout: Per-request timeout in seconds. |
| 75 | + """ |
| 76 | + |
| 77 | + def __init__( |
| 78 | + self, http_url: str = "http://localhost:9094", timeout: float = 10.0 |
| 79 | + ) -> None: |
| 80 | + self.http_url = http_url.rstrip("/") |
| 81 | + self.timeout = timeout |
| 82 | + |
| 83 | + async def validate( |
| 84 | + self, |
| 85 | + contract: dict[str, Any], |
| 86 | + value: Union[dict[str, Any], list[Any], str, bytes], |
| 87 | + ) -> ValidationResult: |
| 88 | + """Dry-run ``contract`` against ``value``. |
| 89 | +
|
| 90 | + ``value`` may be a JSON-serializable object (sent as ``value``) |
| 91 | + or raw bytes/str (sent as ``value_b64``-style, encoded inline). |
| 92 | + """ |
| 93 | + body: dict[str, Any] = {"contract": contract} |
| 94 | + if isinstance(value, (bytes, bytearray)): |
| 95 | + body["value_string"] = value.decode("utf-8", errors="replace") |
| 96 | + elif isinstance(value, str): |
| 97 | + body["value_string"] = value |
| 98 | + else: |
| 99 | + body["value"] = value |
| 100 | + |
| 101 | + url = f"{self.http_url}/api/v1/contracts/validate" |
| 102 | + status, payload = await self._post(url, body) |
| 103 | + |
| 104 | + if status == 200: |
| 105 | + data = payload or {} |
| 106 | + return ValidationResult( |
| 107 | + valid=True, |
| 108 | + schema_id=data.get("schema_id"), |
| 109 | + errors=[], |
| 110 | + ) |
| 111 | + if status == 400: |
| 112 | + data = payload or {} |
| 113 | + errs = [ |
| 114 | + ValidationError.from_json(e) |
| 115 | + for e in data.get("errors", []) |
| 116 | + ] |
| 117 | + return ValidationResult( |
| 118 | + valid=False, |
| 119 | + schema_id=data.get("schema_id"), |
| 120 | + errors=errs, |
| 121 | + ) |
| 122 | + raise ContractsError( |
| 123 | + f"validate -> HTTP {status}: {json.dumps(payload)[:512]}" |
| 124 | + ) |
| 125 | + |
| 126 | + async def _post(self, url: str, body: dict[str, Any]) -> tuple[int, Any]: |
| 127 | + if _HAS_AIOHTTP: |
| 128 | + timeout = aiohttp.ClientTimeout(total=self.timeout) |
| 129 | + async with aiohttp.ClientSession(timeout=timeout) as session: |
| 130 | + async with session.post(url, json=body) as resp: |
| 131 | + text = await resp.text() |
| 132 | + payload: Any = None |
| 133 | + if text: |
| 134 | + try: |
| 135 | + payload = json.loads(text) |
| 136 | + except json.JSONDecodeError: |
| 137 | + payload = {"raw": text} |
| 138 | + return resp.status, payload |
| 139 | + else: |
| 140 | + import urllib.request |
| 141 | + import urllib.error |
| 142 | + |
| 143 | + data = json.dumps(body).encode("utf-8") |
| 144 | + req = urllib.request.Request( |
| 145 | + url, |
| 146 | + data=data, |
| 147 | + headers={"Content-Type": "application/json"}, |
| 148 | + method="POST", |
| 149 | + ) |
| 150 | + |
| 151 | + def _sync() -> tuple[int, Any]: |
| 152 | + try: |
| 153 | + with urllib.request.urlopen(req, timeout=self.timeout) as resp: |
| 154 | + text = resp.read().decode("utf-8") |
| 155 | + return resp.status, json.loads(text) if text else None |
| 156 | + except urllib.error.HTTPError as e: |
| 157 | + text = e.read().decode("utf-8", errors="replace") |
| 158 | + try: |
| 159 | + return e.code, json.loads(text) |
| 160 | + except json.JSONDecodeError: |
| 161 | + return e.code, {"raw": text} |
| 162 | + |
| 163 | + return await asyncio.to_thread(_sync) |
| 164 | + |
| 165 | + |
| 166 | +__all__ = [ |
| 167 | + "ContractsClient", |
| 168 | + "ContractsError", |
| 169 | + "ValidationError", |
| 170 | + "ValidationResult", |
| 171 | +] |
0 commit comments