From 381f32a87e2c4fabd552da21177592501bcdb826 Mon Sep 17 00:00:00 2001 From: Man Alin Date: Tue, 1 Dec 2026 11:07:58 +0000 Subject: [PATCH] fix: record status and error type for failed attempts Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- docs/opentelemetry.md | 1 + openfga_sdk/api_client.py | 5 +-- openfga_sdk/sync/api_client.py | 5 +-- openfga_sdk/telemetry/attributes.py | 35 +++++++++++++++---- openfga_sdk/telemetry/configuration.py | 28 +++++++++++++++ test/network_retry_test.py | 47 ++++++++++++++++++++++++++ test/telemetry/attributes_test.py | 29 ++++++++++++++++ test/telemetry/configuration_test.py | 3 +- 8 files changed, 141 insertions(+), 12 deletions(-) diff --git a/docs/opentelemetry.md b/docs/opentelemetry.md index ce4ca6be..6623912e 100644 --- a/docs/opentelemetry.md +++ b/docs/opentelemetry.md @@ -39,6 +39,7 @@ If you configure the OpenTelemetry SDK, these metrics will be exported and sent | `fga-client.request.store_id` | string | Yes | Store ID that was sent as part of the request | | `fga-client.response.model_id` | string | Yes | Authorization model ID that the FGA server used | | `fga-client.user` | string | No | User associated with the action of the request for check and list users | +| `error.type` | string | Yes | Error class for a failed request: an HTTP status code or exception type | | `http.client.request.duration` | int | No | Duration for the SDK to complete the request, in milliseconds | | `http.host` | string | Yes | Host identifier of the origin the request was sent to | | `http.request.method` | string | Yes | HTTP method for the request | diff --git a/openfga_sdk/api_client.py b/openfga_sdk/api_client.py index 8afbd0c1..0858746f 100644 --- a/openfga_sdk/api_client.py +++ b/openfga_sdk/api_client.py @@ -294,7 +294,7 @@ async def __call_api( ) except (RateLimitExceededError, ServiceException) as e: _telemetry_attributes = TelemetryAttributes.fromResponse( - response=e.body.decode("utf-8"), + response=e, credentials=self.configuration.credentials, attributes=_telemetry_attributes, start=start, @@ -338,11 +338,12 @@ async def __call_api( except aiohttp.ClientSSLError: # Also a network error, but retrying won't fix it raise - except rest.NETWORK_ERRORS: + except rest.NETWORK_ERRORS as e: _telemetry_attributes = TelemetryAttributes.fromResponse( credentials=self.configuration.credentials, attributes=_telemetry_attributes, start=start, + error=e, ) self._telemetry.metrics.request( diff --git a/openfga_sdk/sync/api_client.py b/openfga_sdk/sync/api_client.py index 61b6108d..0970e47c 100644 --- a/openfga_sdk/sync/api_client.py +++ b/openfga_sdk/sync/api_client.py @@ -292,7 +292,7 @@ def __call_api( ) except (RateLimitExceededError, ServiceException) as e: _telemetry_attributes = TelemetryAttributes.fromResponse( - response=e.body.decode("utf-8"), + response=e, credentials=self.configuration.credentials, attributes=_telemetry_attributes, start=start, @@ -333,11 +333,12 @@ def __call_api( if isinstance(operation_name, str): e.operation_name = operation_name.lower() raise - except rest.NETWORK_ERRORS: + except rest.NETWORK_ERRORS as e: _telemetry_attributes = TelemetryAttributes.fromResponse( credentials=self.configuration.credentials, attributes=_telemetry_attributes, start=start, + error=e, ) self._telemetry.metrics.request( diff --git a/openfga_sdk/telemetry/attributes.py b/openfga_sdk/telemetry/attributes.py index 02451c1f..8c17dda4 100644 --- a/openfga_sdk/telemetry/attributes.py +++ b/openfga_sdk/telemetry/attributes.py @@ -38,6 +38,9 @@ class TelemetryAttributes: fga_client_user: TelemetryAttribute = TelemetryAttribute( name="fga-client.user", ) + error_type: TelemetryAttribute = TelemetryAttribute( + name="error.type", + ) http_client_request_duration: TelemetryAttribute = TelemetryAttribute( name="http.client.request.duration", format="int", @@ -78,6 +81,7 @@ class TelemetryAttributes: fga_client_request_store_id, fga_client_response_model_id, fga_client_user, + error_type, http_client_request_duration, http_host, http_request_method, @@ -277,6 +281,7 @@ def fromResponse( credentials: Credentials | None = None, attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, start: float | None = None, + error: BaseException | None = None, ) -> dict[TelemetryAttribute, str | bool | int | float]: response_model_id = None response_query_duration = None @@ -290,13 +295,26 @@ def fromResponse( (time.time() - start) * 1000 ) + if error is not None: + error_class = type(error) + error_name = error_class.__qualname__ + if error_class.__module__ != "builtins": + error_name = f"{error_class.__module__}.{error_name}" + _attributes[TelemetryAttributes.error_type] = error_name + _attributes.pop(TelemetryAttributes.http_response_status_code, None) + _attributes.pop(TelemetryAttributes.fga_client_response_model_id, None) + _attributes.pop(TelemetryAttributes.http_server_request_duration, None) + if isinstance(response, ApiException): if response.status is not None: - _attributes[TelemetryAttributes.http_response_status_code] = int( - response.status - ) + status = int(response.status) + _attributes[TelemetryAttributes.http_response_status_code] = status + if status >= 400: + _attributes[TelemetryAttributes.error_type] = str(status) + else: + _attributes.pop(TelemetryAttributes.error_type, None) - if response.body is not None: + if isinstance(response.body, dict): response_model_id = response.body.get( "openfga-authorization-model-id" ) or response.body.get("openfga_authorization_model_id") @@ -304,9 +322,12 @@ def fromResponse( if response is not None: if hasattr(response, "status"): - _attributes[TelemetryAttributes.http_response_status_code] = int( - response.status - ) + status = int(response.status) + _attributes[TelemetryAttributes.http_response_status_code] = status + if status >= 400: + _attributes[TelemetryAttributes.error_type] = str(status) + else: + _attributes.pop(TelemetryAttributes.error_type, None) if hasattr(response, "getheader") and callable(response.getheader): response_model_id = response.getheader("openfga-authorization-model-id") diff --git a/openfga_sdk/telemetry/configuration.py b/openfga_sdk/telemetry/configuration.py index 40958e88..25d7c66a 100644 --- a/openfga_sdk/telemetry/configuration.py +++ b/openfga_sdk/telemetry/configuration.py @@ -23,6 +23,7 @@ def __init__( fga_client_request_store_id: bool | None = None, fga_client_response_model_id: bool | None = None, fga_client_user: bool | None = None, + error_type: bool | None = None, http_client_request_duration: bool | None = None, http_host: bool | None = None, http_request_method: bool | None = None, @@ -44,6 +45,7 @@ def __init__( :param fga_client_request_store_id: The `fga-client.request.store_id` attribute includes the store ID that was sent as part of the request, if any. :param fga_client_response_model_id: The `fga-client.response.model_id` attribute includes the authorization model ID that the FGA server used. :param fga_client_user: The `fga-client.user` attribute includes the user associated with the request, if any. + :param error_type: The `error.type` attribute includes the type of error that ended a request without a response. :param http_client_request_duration: The `http.client.request.duration` attribute includes the duration of the request from the client's perspective. :param http_host: The `http.host` attribute includes the host name of the request. :param http_request_method: The `http.request.method` attribute includes the HTTP method of the request. @@ -94,6 +96,9 @@ def __init__( if fga_client_user is not None: self._state[TelemetryAttributes.fga_client_user] = fga_client_user + if error_type is not None: + self._state[TelemetryAttributes.error_type] = error_type + if http_client_request_duration is not None: self._state[TelemetryAttributes.http_client_request_duration] = ( http_client_request_duration @@ -276,6 +281,27 @@ def fga_client_user(self, value: bool): self._valid = None # Reset the validation state self._state[TelemetryAttributes.fga_client_user] = value + @property + def error_type(self) -> bool: + """ + Get the configuration for the `error.type` attribute. + + :return: The configuration for the `error.type` attribute. + """ + + return self._state[TelemetryAttributes.error_type] + + @error_type.setter + def error_type(self, value: bool): + """ + Set the configuration for the `error.type` attribute. + + :param value: The configuration for the `error.type` attribute. + """ + + self._valid = None # Reset the validation state + self._state[TelemetryAttributes.error_type] = value + @property def http_client_request_duration(self) -> bool: """ @@ -479,6 +505,7 @@ def clear(self) -> None: TelemetryAttributes.fga_client_request_store_id: False, TelemetryAttributes.fga_client_response_model_id: False, TelemetryAttributes.fga_client_user: False, + TelemetryAttributes.error_type: False, TelemetryAttributes.http_client_request_duration: False, TelemetryAttributes.http_host: False, TelemetryAttributes.http_request_method: False, @@ -616,6 +643,7 @@ def getSdkDefaults() -> dict[TelemetryAttribute | str, bool]: TelemetryAttributes.fga_client_request_store_id: True, TelemetryAttributes.fga_client_response_model_id: True, TelemetryAttributes.fga_client_user: False, + TelemetryAttributes.error_type: True, TelemetryAttributes.http_client_request_duration: False, TelemetryAttributes.http_host: True, TelemetryAttributes.http_request_method: True, diff --git a/test/network_retry_test.py b/test/network_retry_test.py index 3dfb40d3..e02f8229 100644 --- a/test/network_retry_test.py +++ b/test/network_retry_test.py @@ -14,6 +14,8 @@ from openfga_sdk.rest import RESTClientObject as AsyncRESTClientObject from openfga_sdk.sync.api_client import ApiClient as SyncApiClient from openfga_sdk.sync.open_fga_api import OpenFgaApi as SyncOpenFgaApi +from openfga_sdk.telemetry.attributes import TelemetryAttributes +from openfga_sdk.telemetry.metrics import TelemetryMetrics CALL_ARGS = {"response_types_map": {}, "_return_http_data_only": True} @@ -35,6 +37,18 @@ ) +@pytest.fixture +def request_metric_attributes(monkeypatch): + """The attributes of every request metric recorded.""" + records = [] + + def request(self, attributes, configuration=None): + records.append(dict(attributes)) + + monkeypatch.setattr(TelemetryMetrics, "request", request) + return records + + def make_configuration(url, **kwargs): return Configuration(api_url=url, retry_params=RetryParams(max_retry=1), **kwargs) @@ -216,3 +230,36 @@ def test_sync_token_request_uses_client_retry_params(server, sleeps): SyncOpenFgaApi(client).list_stores() assert server.requests == ["POST", "POST"] + + +@pytest.mark.asyncio +async def test_async_attempt_metrics_carry_status_and_error_type( + server, sleeps, request_metric_attributes +): + server.actions.extend(["503", "drop"]) + async with AsyncApiClient(make_configuration(server.url)) as client: + with pytest.raises(aiohttp.ServerDisconnectedError): + await client.call_api("/check", "POST", **CALL_ARGS) + + assert len(request_metric_attributes) == 2 + first, second = request_metric_attributes + assert first[TelemetryAttributes.http_response_status_code] == 503 + assert first[TelemetryAttributes.error_type] == "503" + assert second[TelemetryAttributes.error_type].endswith("ServerDisconnectedError") + assert TelemetryAttributes.http_response_status_code not in second + + +def test_sync_attempt_metrics_carry_status_and_error_type( + server, sleeps, request_metric_attributes +): + server.actions.extend(["503", "drop"]) + with SyncApiClient(make_configuration(server.url)) as client: + with pytest.raises(urllib3.exceptions.ProtocolError): + client.call_api("/check", "POST", **CALL_ARGS) + + assert len(request_metric_attributes) == 2 + first, second = request_metric_attributes + assert first[TelemetryAttributes.http_response_status_code] == 503 + assert first[TelemetryAttributes.error_type] == "503" + assert second[TelemetryAttributes.error_type].endswith("ProtocolError") + assert TelemetryAttributes.http_response_status_code not in second diff --git a/test/telemetry/attributes_test.py b/test/telemetry/attributes_test.py index 4484c57d..16bd336d 100644 --- a/test/telemetry/attributes_test.py +++ b/test/telemetry/attributes_test.py @@ -7,6 +7,7 @@ from urllib3 import HTTPResponse from openfga_sdk.credentials import CredentialConfiguration, Credentials +from openfga_sdk.exceptions import ApiException from openfga_sdk.models.batch_check_request import BatchCheckRequest from openfga_sdk.models.check_request import CheckRequest from openfga_sdk.rest import RESTResponse @@ -181,3 +182,31 @@ def test_from_body_with_other_body(telemetry_attributes): attributes = telemetry_attributes.fromBody(body=body) assert attributes == {} + + +def test_from_response_with_api_exception_status(telemetry_attributes): + response = ApiException(status=503, reason="Service Unavailable") + response.body = b"{}" + + attributes = telemetry_attributes.fromResponse(response=response) + + assert attributes[TelemetryAttributes.http_response_status_code] == 503 + assert attributes[TelemetryAttributes.error_type] == "503" + + +def test_from_response_with_error_clears_response_attributes(telemetry_attributes): + attributes = { + TelemetryAttributes.http_response_status_code: 503, + TelemetryAttributes.fga_client_response_model_id: "model_123", + TelemetryAttributes.http_server_request_duration: "50", + } + + result = telemetry_attributes.fromResponse( + attributes=attributes, + error=ValueError("failed"), + ) + + assert result[TelemetryAttributes.error_type] == "ValueError" + assert TelemetryAttributes.http_response_status_code not in result + assert TelemetryAttributes.fga_client_response_model_id not in result + assert TelemetryAttributes.http_server_request_duration not in result diff --git a/test/telemetry/configuration_test.py b/test/telemetry/configuration_test.py index 7b3761a4..0d385a6a 100644 --- a/test/telemetry/configuration_test.py +++ b/test/telemetry/configuration_test.py @@ -293,7 +293,7 @@ def test_default_telemetry_metric_configuration(): metric_config = TelemetryMetricConfiguration.getSdkDefaults() assert isinstance(metric_config, dict) - assert len(metric_config) == 16 + assert len(metric_config) == 17 assert ( metric_config[TelemetryAttributes.fga_client_request_batch_check_size] is False @@ -304,6 +304,7 @@ def test_default_telemetry_metric_configuration(): assert metric_config[TelemetryAttributes.fga_client_request_store_id] is True assert metric_config[TelemetryAttributes.fga_client_response_model_id] is True assert metric_config[TelemetryAttributes.fga_client_user] is False + assert metric_config[TelemetryAttributes.error_type] is True assert metric_config[TelemetryAttributes.http_client_request_duration] is False assert metric_config[TelemetryAttributes.http_host] is True assert metric_config[TelemetryAttributes.http_request_method] is True