Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0).

## Unreleased

Nothing.
### Fixed

- Fixed uncaught `ValueError` in the size metrics when a request or response has
a `Content-Length` header that is not a valid integer. The size is now
observed as `0`. Raised in
[#404](https://github.com/trallnag/prometheus-fastapi-instrumentator/issues/404).

## [8.1.0](https://github.com/trallnag/prometheus-fastapi-instrumentator/compare/v8.0.2...v8.1.0) / 2026-07-26

Expand Down
47 changes: 36 additions & 11 deletions src/prometheus_fastapi_instrumentator/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,25 @@ def __init__(
self.modified_duration_without_streaming = modified_duration_without_streaming


def _parse_content_length(value: Union[str, int]) -> int:
"""Converts a `Content-Length` header value to an integer.

The value comes from the client or the application, so it is not guaranteed
to be a valid integer.

Args:
value (str or int): Value of the header, or the default if it is absent.

Returns:
int: Parsed value, or `0` if the value is not a valid integer.
"""

try:
return int(value)
except ValueError:
return 0


def _build_label_attribute_names(
should_include_handler: bool,
should_include_method: bool,
Expand Down Expand Up @@ -289,16 +308,18 @@ def request_size(
)

def instrumentation(info: Info) -> None:
content_length = info.request.headers.get("Content-Length", 0)
content_length = _parse_content_length(
info.request.headers.get("Content-Length", 0)
)
if label_names:
label_values = [
getattr(info, attribute_name)
for attribute_name in info_attribute_names
]

METRIC.labels(*label_values).observe(int(content_length))
METRIC.labels(*label_values).observe(content_length)
else:
METRIC.observe(int(content_length))
METRIC.observe(content_length)

return instrumentation
except ValueError as e:
Expand Down Expand Up @@ -384,7 +405,9 @@ def response_size(

def instrumentation(info: Info) -> None:
if info.response and hasattr(info.response, "headers"):
content_length = info.response.headers.get("Content-Length", 0)
content_length = _parse_content_length(
info.response.headers.get("Content-Length", 0)
)
else:
content_length = 0

Expand All @@ -394,9 +417,9 @@ def instrumentation(info: Info) -> None:
for attribute_name in info_attribute_names
]

METRIC.labels(*label_values).observe(int(content_length))
METRIC.labels(*label_values).observe(content_length)
else:
METRIC.observe(int(content_length))
METRIC.observe(content_length)

return instrumentation
except ValueError as e:
Expand Down Expand Up @@ -487,17 +510,19 @@ def instrumentation(info: Info) -> None:
else:
response_cl = 0

content_length = int(request_cl) + int(response_cl)
content_length = _parse_content_length(request_cl) + _parse_content_length(
response_cl
)

if label_names:
label_values = [
getattr(info, attribute_name)
for attribute_name in info_attribute_names
]

METRIC.labels(*label_values).observe(int(content_length))
METRIC.labels(*label_values).observe(content_length)
else:
METRIC.observe(int(content_length))
METRIC.observe(content_length)

return instrumentation
except ValueError as e:
Expand Down Expand Up @@ -794,7 +819,7 @@ def instrumentation(info: Info) -> None:
for attribute_name in _map_label_name_value(in_size_names)
] + list(custom_labels.values())
IN_SIZE.labels(*label_values).observe(
int(info.request.headers.get("Content-Length", 0))
_parse_content_length(info.request.headers.get("Content-Length", 0))
)

label_values = [
Expand All @@ -803,7 +828,7 @@ def instrumentation(info: Info) -> None:
] + list(custom_labels.values())
if info.response and hasattr(info.response, "headers"):
OUT_SIZE.labels(*label_values).observe(
int(info.response.headers.get("Content-Length", 0))
_parse_content_length(info.response.headers.get("Content-Length", 0))
)
else:
OUT_SIZE.labels(*label_values).observe(0)
Expand Down
58 changes: 58 additions & 0 deletions tests/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,64 @@ def test_request_size_no_cl():
assert b"http_request_size_bytes_count{" in response.content


# ------------------------------------------------------------------------------
# Malformed Content-Length


SIZE_INSTRUMENTATIONS = [
metrics.request_size,
metrics.response_size,
metrics.combined_size,
metrics.default,
]


def test_parse_content_length():
assert metrics._parse_content_length("123") == 123
assert metrics._parse_content_length(0) == 0
assert metrics._parse_content_length("abc") == 0
assert metrics._parse_content_length("") == 0


@pytest.mark.parametrize("instrumentation", SIZE_INSTRUMENTATIONS)
def test_malformed_request_content_length(instrumentation):
app = create_app()
Instrumentator().add(instrumentation()).instrument(app)
client = TestClient(app)

response = client.get("/", headers={"Content-Length": "abc"})

assert response.status_code == 200


@pytest.mark.parametrize("instrumentation", SIZE_INSTRUMENTATIONS)
def test_malformed_response_content_length(instrumentation):
app = create_app()

@app.get("/malformed_content_length")
def read_malformed_content_length():
return responses.Response(headers={"Content-Length": "abc"})

Instrumentator().add(instrumentation()).instrument(app)
client = TestClient(app)

response = client.get("/malformed_content_length")

assert response.status_code == 200


def test_malformed_request_content_length_observes_zero():
app = create_app()
Instrumentator().add(metrics.request_size()).instrument(app)
client = TestClient(app)

client.get("/", headers={"Content-Length": "abc"})

labels = {"handler": "/", "method": "GET", "status": "2xx"}
assert REGISTRY.get_sample_value("http_request_size_bytes_count", labels) == 1
assert REGISTRY.get_sample_value("http_request_size_bytes_sum", labels) == 0


# ------------------------------------------------------------------------------
# response_size

Expand Down
Loading