|
| 1 | +"""HTTP client patch for handling unknown field errors. |
| 2 | +
|
| 3 | +This module provides functionality to automatically retry API requests when the server |
| 4 | +rejects unknown or unexpected fields. This enables backward compatibility when using |
| 5 | +newer SDK versions with older server versions. |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +from typing import Any, Set |
| 10 | + |
| 11 | +import httpx |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def patch_client_for_unknown_field_retry(client: httpx.Client) -> None: |
| 17 | + """Patch an httpx.Client instance to automatically retry on unknown field errors. |
| 18 | +
|
| 19 | + When the server returns a 400/422 error with unrecognized_keys, this automatically |
| 20 | + retries the request with those fields removed. |
| 21 | +
|
| 22 | + Args: |
| 23 | + client: The httpx.Client instance to patch |
| 24 | +
|
| 25 | + Example: |
| 26 | + >>> client = httpx.Client() |
| 27 | + >>> patch_client_for_unknown_field_retry(client) |
| 28 | + >>> # Now all requests through this client will handle unknown field errors |
| 29 | + """ |
| 30 | + original_request = client.request |
| 31 | + |
| 32 | + def request_with_retry( |
| 33 | + method: str, url: str | httpx.URL, **kwargs: Any |
| 34 | + ) -> httpx.Response: |
| 35 | + """Wrapped request that handles unknown field errors with retry.""" |
| 36 | + response = original_request(method, url, **kwargs) |
| 37 | + |
| 38 | + # Retry if server rejected unrecognized keys |
| 39 | + if response.status_code in [400, 422] and "json" in kwargs: |
| 40 | + try: |
| 41 | + unknown_keys = _extract_unknown_keys(response) |
| 42 | + if unknown_keys: |
| 43 | + logger.warning( |
| 44 | + "Server rejected unrecognized keys %s for %s %s. Retrying without these fields.", |
| 45 | + unknown_keys, |
| 46 | + method, |
| 47 | + url, |
| 48 | + ) |
| 49 | + kwargs["json"] = _remove_fields(kwargs["json"], unknown_keys) |
| 50 | + response = original_request(method, url, **kwargs) |
| 51 | + except Exception as e: |
| 52 | + logger.debug("Failed to parse unknown field error: %s", e) |
| 53 | + |
| 54 | + return response |
| 55 | + |
| 56 | + client.request = request_with_retry # type: ignore[method-assign] |
| 57 | + |
| 58 | + |
| 59 | +def patch_async_client_for_unknown_field_retry(client: httpx.AsyncClient) -> None: |
| 60 | + """Patch an httpx.AsyncClient instance to automatically retry on unknown field errors. |
| 61 | +
|
| 62 | + Async version of patch_client_for_unknown_field_retry. |
| 63 | +
|
| 64 | + Args: |
| 65 | + client: The httpx.AsyncClient instance to patch |
| 66 | + """ |
| 67 | + original_request = client.request |
| 68 | + |
| 69 | + async def request_with_retry( |
| 70 | + method: str, url: str | httpx.URL, **kwargs: Any |
| 71 | + ) -> httpx.Response: |
| 72 | + """Wrapped async request that handles unknown field errors with retry.""" |
| 73 | + response = await original_request(method, url, **kwargs) |
| 74 | + |
| 75 | + # Retry if server rejected unrecognized keys |
| 76 | + if response.status_code in [400, 422] and "json" in kwargs: |
| 77 | + try: |
| 78 | + unknown_keys = _extract_unknown_keys(response) |
| 79 | + if unknown_keys: |
| 80 | + logger.warning( |
| 81 | + "Server rejected unrecognized keys %s for %s %s. Retrying without these fields.", |
| 82 | + unknown_keys, |
| 83 | + method, |
| 84 | + url, |
| 85 | + ) |
| 86 | + kwargs["json"] = _remove_fields(kwargs["json"], unknown_keys) |
| 87 | + response = await original_request(method, url, **kwargs) |
| 88 | + except Exception as e: |
| 89 | + logger.debug("Failed to parse unknown field error: %s", e) |
| 90 | + |
| 91 | + return response |
| 92 | + |
| 93 | + client.request = request_with_retry # type: ignore[method-assign] |
| 94 | + |
| 95 | + |
| 96 | +def _extract_unknown_keys(response: httpx.Response) -> Set[str]: |
| 97 | + """Extract unknown keys from server error response. |
| 98 | +
|
| 99 | + Args: |
| 100 | + response: The HTTP response from the server |
| 101 | +
|
| 102 | + Returns: |
| 103 | + Set of field names that were rejected as unrecognized |
| 104 | + """ |
| 105 | + body = response.json() |
| 106 | + if isinstance(body, dict) and "error" in body: |
| 107 | + unknown_keys = set() |
| 108 | + for error in body.get("error", []): |
| 109 | + if isinstance(error, dict) and error.get("code") == "unrecognized_keys": |
| 110 | + unknown_keys.update(error.get("keys", [])) |
| 111 | + return unknown_keys |
| 112 | + return set() |
| 113 | + |
| 114 | + |
| 115 | +def _remove_fields(data: Any, fields: Set[str]) -> Any: |
| 116 | + """Remove specified fields from nested dict/list structures. |
| 117 | +
|
| 118 | + Args: |
| 119 | + data: The data structure to filter (dict, list, or primitive) |
| 120 | + fields: Set of field names to remove |
| 121 | +
|
| 122 | + Returns: |
| 123 | + Filtered data structure with specified fields removed |
| 124 | + """ |
| 125 | + if isinstance(data, dict): |
| 126 | + return { |
| 127 | + k: _remove_fields(v, fields) for k, v in data.items() if k not in fields |
| 128 | + } |
| 129 | + elif isinstance(data, list): |
| 130 | + return [_remove_fields(item, fields) for item in data] |
| 131 | + else: |
| 132 | + return data |
0 commit comments