diff --git a/README.md b/README.md index 6cdbb98..509f529 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,11 @@ Optionally, you can customize Judoscale in `settings.py`: JUDOSCALE = { # Log level defaults to ENV["LOG_LEVEL"] or "INFO". "LOG_LEVEL": "DEBUG", + # Leave requests with a body over this many bytes out of queue time. Some + # web servers read the whole body before the app sees the request, so a + # slow upload shows up as queue time. Defaults to 100_000 (100 KB). + # Set to None to count every request. + "MAX_REQUEST_SIZE_BYTES": 100_000, } ``` @@ -87,6 +92,11 @@ Optionally, you can override Judoscale's own configuration via your application' JUDOSCALE = { # Log level defaults to ENV["LOG_LEVEL"] or "INFO". "LOG_LEVEL": "DEBUG", + # Leave requests with a body over this many bytes out of queue time. Some + # web servers read the whole body before the app sees the request, so a + # slow upload shows up as queue time. Defaults to 100_000 (100 KB). + # Set to None to count every request. + "MAX_REQUEST_SIZE_BYTES": 100_000, } ``` diff --git a/judoscale/core/config.py b/judoscale/core/config.py index 2f598e4..da6d808 100644 --- a/judoscale/core/config.py +++ b/judoscale/core/config.py @@ -6,7 +6,11 @@ from judoscale.core.logger import logger from judoscale.core.platform import Platform -DEFAULTS = {"REPORT_INTERVAL_SECONDS": 10, "LOG_LEVEL": "WARN"} +DEFAULTS = { + "LOG_LEVEL": "WARN", + "REPORT_INTERVAL_SECONDS": 10, + "MAX_REQUEST_SIZE_BYTES": 100_000, +} class Config(UserDict): @@ -48,6 +52,7 @@ def update(self, new_config: Mapping): self[k].update(v) else: self[k] = v + self._coerce_max_request_size_bytes() self._prepare_logging() def merge(self, new_config: Mapping): @@ -60,8 +65,29 @@ def for_report(self): return { "log_level": self["LOG_LEVEL"], "report_interval_seconds": self["REPORT_INTERVAL_SECONDS"], + "max_request_size_bytes": self["MAX_REQUEST_SIZE_BYTES"], } + def _coerce_max_request_size_bytes(self): + # Metric.for_web compares this to every request's size, so a value of + # the wrong type would fail every request. + value = self["MAX_REQUEST_SIZE_BYTES"] + + if value is None or value is False: + # False turns the cutoff off, as in Ruby. + self["MAX_REQUEST_SIZE_BYTES"] = None + elif isinstance(value, int) and not isinstance(value, bool): + pass + elif isinstance(value, str) and value.strip().isdigit(): + self["MAX_REQUEST_SIZE_BYTES"] = int(value) + else: + default = DEFAULTS["MAX_REQUEST_SIZE_BYTES"] + logger.warning( + f"Invalid MAX_REQUEST_SIZE_BYTES {value!r}, using {default}. " + "Set it to a number of bytes, or None to count every request." + ) + self["MAX_REQUEST_SIZE_BYTES"] = default + def _prepare_logging(self): log_level = logging.getLevelName(self["LOG_LEVEL"].upper()) logger.setLevel(log_level) diff --git a/judoscale/core/metric.py b/judoscale/core/metric.py index 0153bac..55635c6 100644 --- a/judoscale/core/metric.py +++ b/judoscale/core/metric.py @@ -1,8 +1,10 @@ import time from dataclasses import dataclass from datetime import datetime, timezone -from typing import Optional, Tuple +from typing import Optional, Tuple, Union +from judoscale.core.config import Config +from judoscale.core.config import config as judoconfig from judoscale.core.logger import logger # Adapted from https://github.com/scoutapp/scout_apm_python/blob/86d14920a59a7a3b5dfffe680586646ee29bdd7a/src/scout_apm/core/web_requests.py#L139-L162 # noqa: E501 @@ -60,7 +62,12 @@ def new(cls, start_ms: int, **kwargs) -> "Metric": return cls(timestamp=now, value=latency_ms, **kwargs) @classmethod - def for_web(cls, header_value: str) -> Optional["Metric"]: + def for_web( + cls, + header_value: str, + content_length: Optional[Union[int, str]] = None, + config: Optional[Config] = None, + ) -> Optional["Metric"]: """ Parse the X-Request-Start header value and return a Metric instance. @@ -73,8 +80,32 @@ def for_web(cls, header_value: str) -> Optional["Metric"]: Calculate how long a request has been waiting to be handled, log and return a Metric instance. + + Return None when the request's Content-Length is over the config's + MAX_REQUEST_SIZE_BYTES. Some web servers, such as waitress, read the + whole request body before they call the app, so a slow upload of a + large body shows up as queue time that says nothing about capacity. + + content_length: + The request's Content-Length header, as a string or an int. + + config: + The Judoscale config to read settings from. Defaults to + Judoscale's own. """ + if config is None: + config = judoconfig + + try: + request_size = int(content_length or 0) + except ValueError: + request_size = 0 + + max_request_size_bytes = config["MAX_REQUEST_SIZE_BYTES"] + if max_request_size_bytes is not None and request_size > max_request_size_bytes: + return None + if header_value.startswith("t="): header_value = header_value[2:] diff --git a/judoscale/django/middleware.py b/judoscale/django/middleware.py index 358d289..1c89d26 100644 --- a/judoscale/django/middleware.py +++ b/judoscale/django/middleware.py @@ -26,8 +26,9 @@ def __init__(self, get_response): def __call__(self, request): with self.track_utilization(): request_start_header = request.META.get("HTTP_X_REQUEST_START", "") + content_length = request.META.get("CONTENT_LENGTH") - if metric := Metric.for_web(request_start_header): + if metric := Metric.for_web(request_start_header, content_length): self.collector.add(metric) reporter.ensure_running() diff --git a/judoscale/flask/judoscale.py b/judoscale/flask/judoscale.py index 527a25c..4caa796 100644 --- a/judoscale/flask/judoscale.py +++ b/judoscale/flask/judoscale.py @@ -16,7 +16,7 @@ def store_queue_time_metric(collector: WebMetricsCollector): def inner(): request_start_header = request.headers.get("x-request-start", "") - if metric := Metric.for_web(request_start_header): + if metric := Metric.for_web(request_start_header, request.content_length): collector.add(metric) reporter.ensure_running() diff --git a/sample-apps/django_sample/tests/tests.py b/sample-apps/django_sample/tests/tests.py index 6cace58..cdbede8 100644 --- a/sample-apps/django_sample/tests/tests.py +++ b/sample-apps/django_sample/tests/tests.py @@ -76,3 +76,24 @@ def test_reporter_captures_metrics(self): self.assertEqual(metrics[2].measurement, "qt") self.assertGreaterEqual(metrics[2].value, 0) self.assertGreater(metrics[2].timestamp, now) + + def test_reporter_skips_queue_time_for_large_requests(self): + now = datetime.datetime.now().timestamp() + + response = client.post( + "/", + data=b"x" * 100_001, + content_type="application/octet-stream", + HTTP_X_REQUEST_START=f"{now}", + HTTP_X_REQUEST_ID="00000000-0000-0000-0000-000000000000", + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(reporter.is_running, True) + self.assertEqual(utilization_tracker.is_started, True) + + # no queue time metrics gathered, only app time & utilization + metrics = reporter.all_metrics + self.assertEqual(len(metrics), 2) + self.assertEqual(metrics[0].measurement, "up") + self.assertEqual(metrics[1].measurement, "at") diff --git a/sample-apps/flask_sample/tests.py b/sample-apps/flask_sample/tests.py index 1d83cf1..9b619f3 100644 --- a/sample-apps/flask_sample/tests.py +++ b/sample-apps/flask_sample/tests.py @@ -82,6 +82,28 @@ def test_reporter_captures_metrics(self): self.assertGreaterEqual(metrics[2].value, 0) self.assertGreater(metrics[2].timestamp, now) + def test_reporter_skips_queue_time_for_large_requests(self): + now = time.time() + + response = client.get( + "/", + data=b"x" * 100_001, + headers={ + "X-Request-Start": f"{round(now * 1000)}", + "X-Request-Id": "00000000-0000-0000-0000-000000000000", + }, + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(reporter.is_running, True) + self.assertEqual(utilization_tracker.is_started, True) + + # no queue time metrics gathered, only app time & utilization + metrics = reporter.all_metrics + self.assertEqual(len(metrics), 2) + self.assertEqual(metrics[0].measurement, "up") + self.assertEqual(metrics[1].measurement, "at") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_config.py b/tests/test_config.py index 9761a94..2bcc324 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -192,14 +192,43 @@ def test_for_report(self): "JUDOSCALE_URL": "https://api.example.com", } config = Config.initialize(fake_env) - assert config.for_report == {"log_level": "WARN", "report_interval_seconds": 10} + assert config.for_report == { + "log_level": "WARN", + "report_interval_seconds": 10, + "max_request_size_bytes": 100_000, + } - config.update({"LOG_LEVEL": "ERROR", "REPORT_INTERVAL_SECONDS": 20}) + config.update( + { + "LOG_LEVEL": "ERROR", + "REPORT_INTERVAL_SECONDS": 20, + "MAX_REQUEST_SIZE_BYTES": None, + } + ) assert config.for_report == { "log_level": "ERROR", "report_interval_seconds": 20, + "max_request_size_bytes": None, } + def test_max_request_size_bytes_defaults_to_100k(self): + config = Config(Unknown(""), {}) + assert config["MAX_REQUEST_SIZE_BYTES"] == 100_000 + + def test_update_coerces_max_request_size_bytes(self, caplog): + config = Config(Unknown(""), {}) + + config.update({"MAX_REQUEST_SIZE_BYTES": "5000"}) + assert config["MAX_REQUEST_SIZE_BYTES"] == 5000 + + config.update({"MAX_REQUEST_SIZE_BYTES": False}) + assert config["MAX_REQUEST_SIZE_BYTES"] is None + + for invalid in ["lots", True, 1.5]: + config.update({"MAX_REQUEST_SIZE_BYTES": invalid}) + assert config["MAX_REQUEST_SIZE_BYTES"] == 100_000 + assert "Invalid MAX_REQUEST_SIZE_BYTES 'lots'" in caplog.text + def test_update(self): fake_env = { "DYNO": "worker.1", diff --git a/tests/test_metrics.py b/tests/test_metrics.py index 427cedf..d69e113 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -2,7 +2,10 @@ from pytest import approx +from judoscale.core.config import Config +from judoscale.core.config import config as judoconfig from judoscale.core.metric import Metric +from judoscale.core.platform import Unknown class TestMetricsForWeb: @@ -42,6 +45,38 @@ def test_negative_value(self): def test_garbage_value(self): assert Metric.for_web("t=abc") is None + def test_request_over_max_size(self): + request_start = str(round(time.time() * 1000)) + config = Config(Unknown(""), {}) + + assert Metric.for_web(request_start, "100001", config=config) is None + assert Metric.for_web(request_start, 100_001, config=config) is None + + def test_request_up_to_max_size(self): + request_start = str(round(time.time() * 1000)) + config = Config(Unknown(""), {}) + + assert Metric.for_web(request_start, None, config=config) is not None + assert Metric.for_web(request_start, "", config=config) is not None + assert Metric.for_web(request_start, "512", config=config) is not None + assert Metric.for_web(request_start, 512, config=config) is not None + assert Metric.for_web(request_start, "100000", config=config) is not None + assert Metric.for_web(request_start, "not-a-number", config=config) is not None + + def test_no_max_request_size(self): + request_start = str(round(time.time() * 1000)) + config = Config(Unknown(""), {}) + config.update({"MAX_REQUEST_SIZE_BYTES": None}) + + assert Metric.for_web(request_start, "10000000", config=config) is not None + + def test_max_request_size_from_judoscale_config(self, monkeypatch): + request_start = str(round(time.time() * 1000)) + monkeypatch.setitem(judoconfig, "MAX_REQUEST_SIZE_BYTES", 1_000) + + assert Metric.for_web(request_start, "1000") is not None + assert Metric.for_web(request_start, "1001") is None + class TestMetricsForQueueDepth: def test_for_queue_depth(self):