|
| 1 | +"""Sync and async helpers for ack/nack callbacks on async hook deliveries.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import httpx |
| 9 | + |
| 10 | +from ._errors import CallbackError |
| 11 | +from ._models import CallbackResult |
| 12 | + |
| 13 | + |
| 14 | +def _parse_callback_response( |
| 15 | + response: httpx.Response, |
| 16 | + action: str, |
| 17 | + expected_status: str, |
| 18 | +) -> CallbackResult: |
| 19 | + """Parse an ack/nack HTTP response into a CallbackResult. |
| 20 | +
|
| 21 | + 2xx → parse ``{data: {status}}`` from JSON, ``applied = (status == expected)``. |
| 22 | + 404 → ``CallbackResult(applied=False, status="not_found")``. |
| 23 | + 409 → ``CallbackResult(applied=False, status="conflict")``. |
| 24 | + Other → raise ``CallbackError``. |
| 25 | + """ |
| 26 | + if response.is_success: |
| 27 | + try: |
| 28 | + data = response.json() |
| 29 | + status = data.get("data", {}).get("status", "unknown") |
| 30 | + except Exception: |
| 31 | + status = "unknown" |
| 32 | + return CallbackResult(applied=(status == expected_status), status=status) |
| 33 | + |
| 34 | + if response.status_code == 404: |
| 35 | + return CallbackResult(applied=False, status="not_found") |
| 36 | + if response.status_code == 409: |
| 37 | + return CallbackResult(applied=False, status="conflict") |
| 38 | + |
| 39 | + text = response.text |
| 40 | + suffix = f": {text}" if text else "" |
| 41 | + raise CallbackError( |
| 42 | + f"{action} failed: {response.status_code}{suffix}", |
| 43 | + status_code=response.status_code, |
| 44 | + ) |
| 45 | + |
| 46 | + |
| 47 | +def _prepare_request(body: Any) -> tuple[bytes | None, dict[str, str]]: |
| 48 | + """Prepare content and headers for a callback request.""" |
| 49 | + if body is not None: |
| 50 | + return json.dumps(body).encode(), {"Content-Type": "application/json"} |
| 51 | + return None, {} |
| 52 | + |
| 53 | + |
| 54 | +def ack(url: str, body: Any = None) -> CallbackResult: |
| 55 | + """Acknowledge async processing completion (synchronous). |
| 56 | +
|
| 57 | + Args: |
| 58 | + url: The ack callback URL from ``delivery.ack_url``. |
| 59 | + body: Optional JSON-serializable body to send with the callback. |
| 60 | + Posthook currently ignores ack bodies. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + A ``CallbackResult`` indicating whether the ack was applied. |
| 64 | +
|
| 65 | + Raises: |
| 66 | + CallbackError: For unexpected failures (401, 410, 5xx). |
| 67 | + """ |
| 68 | + content, headers = _prepare_request(body) |
| 69 | + response = httpx.post(url, content=content, headers=headers) |
| 70 | + return _parse_callback_response(response, "ack", "completed") |
| 71 | + |
| 72 | + |
| 73 | +def nack(url: str, body: Any = None) -> CallbackResult: |
| 74 | + """Reject async processing — triggers retry or failure (synchronous). |
| 75 | +
|
| 76 | + Args: |
| 77 | + url: The nack callback URL from ``delivery.nack_url``. |
| 78 | + body: Optional JSON-serializable body explaining the failure. |
| 79 | +
|
| 80 | + Returns: |
| 81 | + A ``CallbackResult`` indicating whether the nack was applied. |
| 82 | +
|
| 83 | + Raises: |
| 84 | + CallbackError: For unexpected failures (401, 410, 5xx). |
| 85 | + """ |
| 86 | + content, headers = _prepare_request(body) |
| 87 | + response = httpx.post(url, content=content, headers=headers) |
| 88 | + return _parse_callback_response(response, "nack", "nacked") |
| 89 | + |
| 90 | + |
| 91 | +async def async_ack(url: str, body: Any = None) -> CallbackResult: |
| 92 | + """Acknowledge async processing completion (asynchronous). |
| 93 | +
|
| 94 | + Args: |
| 95 | + url: The ack callback URL from ``delivery.ack_url``. |
| 96 | + body: Optional JSON-serializable body to send with the callback. |
| 97 | + Posthook currently ignores ack bodies. |
| 98 | +
|
| 99 | + Returns: |
| 100 | + A ``CallbackResult`` indicating whether the ack was applied. |
| 101 | +
|
| 102 | + Raises: |
| 103 | + CallbackError: For unexpected failures (401, 410, 5xx). |
| 104 | + """ |
| 105 | + content, headers = _prepare_request(body) |
| 106 | + async with httpx.AsyncClient() as client: |
| 107 | + response = await client.post(url, content=content, headers=headers) |
| 108 | + return _parse_callback_response(response, "ack", "completed") |
| 109 | + |
| 110 | + |
| 111 | +async def async_nack(url: str, body: Any = None) -> CallbackResult: |
| 112 | + """Reject async processing — triggers retry or failure (asynchronous). |
| 113 | +
|
| 114 | + Args: |
| 115 | + url: The nack callback URL from ``delivery.nack_url``. |
| 116 | + body: Optional JSON-serializable body explaining the failure. |
| 117 | +
|
| 118 | + Returns: |
| 119 | + A ``CallbackResult`` indicating whether the nack was applied. |
| 120 | +
|
| 121 | + Raises: |
| 122 | + CallbackError: For unexpected failures (401, 410, 5xx). |
| 123 | + """ |
| 124 | + content, headers = _prepare_request(body) |
| 125 | + async with httpx.AsyncClient() as client: |
| 126 | + response = await client.post(url, content=content, headers=headers) |
| 127 | + return _parse_callback_response(response, "nack", "nacked") |
0 commit comments