|
| 1 | +"""Negotiated long-poll responses and early transport failure diagnostics.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import time |
| 7 | +from collections.abc import Mapping |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +import httpx |
| 11 | + |
| 12 | +MEDIA_TYPE = "application/vnd.durable-workflow.poll.v1+json" |
| 13 | +ACCEPT = f"{MEDIA_TYPE}, application/json;q=0.9" |
| 14 | +_SCHEMA = "durable-workflow.poll-transport.v1" |
| 15 | +POLL_PATHS = frozenset( |
| 16 | + f"/worker/{kind}-tasks/poll" for kind in ("workflow", "activity", "query", "update-validation") |
| 17 | +) |
| 18 | +_HEADERS = frozenset(("retry-after", "x-durable-workflow-protocol-version")) |
| 19 | +log = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +def unwrap_response(response: httpx.Response) -> httpx.Response: |
| 23 | + if response.headers.get("content-type", "").split(";", 1)[0].strip().lower() != MEDIA_TYPE: |
| 24 | + return response |
| 25 | + |
| 26 | + try: |
| 27 | + envelope = response.json() |
| 28 | + if not isinstance(envelope, dict) or envelope.get("schema") != _SCHEMA: |
| 29 | + raise ValueError("unrecognized poll transport") |
| 30 | + status, headers, body = envelope.get("status"), envelope.get("headers"), envelope.get("body") |
| 31 | + if (type(status) is not int or not 200 <= status < 600 |
| 32 | + or response.status_code not in (200, status) |
| 33 | + or not isinstance(body, dict) or not isinstance(headers, dict) |
| 34 | + or any(key not in _HEADERS or not isinstance(value, str) |
| 35 | + or "\r" in value or "\n" in value for key, value in headers.items())): |
| 36 | + raise ValueError("invalid poll transport result") |
| 37 | + # Apply the original status and retry headers before the normal client |
| 38 | + # error handling. Outer HTTP 200 may have been committed by progress. |
| 39 | + return httpx.Response(status, headers=headers, json=body, request=response.request) |
| 40 | + except (ValueError, TypeError) as error: |
| 41 | + raise httpx.RemoteProtocolError("Invalid worker poll transport response.", request=response.request) from error |
| 42 | + |
| 43 | + |
| 44 | +def warn_early_cutoff(path: str, body: Any, started: float, error: Exception) -> None: |
| 45 | + wait = body.get("timeout_seconds") if isinstance(body, Mapping) else None |
| 46 | + observed = time.monotonic() - started |
| 47 | + if isinstance(wait, bool) or not isinstance(wait, int | float) or wait <= 0 or observed >= wait: |
| 48 | + return |
| 49 | + if isinstance(error, httpx.HTTPStatusError) and error.response.status_code not in (502, 504): |
| 50 | + return |
| 51 | + log.warning( |
| 52 | + "Worker long poll %s ended after %.3fs before its configured wait of %.3fs (%s). " |
| 53 | + "Check proxy and HTTP timeout budgets.", |
| 54 | + path, observed, wait, type(error).__name__, |
| 55 | + ) |
0 commit comments