|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Benchmark the validation middleware Rust sidecar against the Python path.""" |
| 3 | + |
| 4 | +# Standard |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import importlib |
| 8 | +import re |
| 9 | +import statistics |
| 10 | +import subprocess |
| 11 | +import time |
| 12 | +from pathlib import Path |
| 13 | +from typing import Any, Callable |
| 14 | + |
| 15 | +# Third-Party |
| 16 | +from fastapi import HTTPException |
| 17 | + |
| 18 | +# First-Party |
| 19 | +from mcpgateway.config import settings |
| 20 | +from mcpgateway.middleware.validation_middleware import ValidationMiddleware |
| 21 | + |
| 22 | +REPO_ROOT = Path(__file__).resolve().parents[2] |
| 23 | +SIDECAR_MANIFEST = REPO_ROOT / "tools_rust" / "validation_middleware_sidecar" / "Cargo.toml" |
| 24 | + |
| 25 | + |
| 26 | +def _ensure_sidecar_installed() -> Any: |
| 27 | + subprocess.run(["uv", "run", "maturin", "develop", "--release", "--manifest-path", str(SIDECAR_MANIFEST)], check=True, cwd=REPO_ROOT) |
| 28 | + return importlib.import_module("validation_middleware_sidecar") |
| 29 | + |
| 30 | + |
| 31 | +def _build_python_validator(max_param_length: int, dangerous_patterns: list[str]) -> Callable[[Any], None]: |
| 32 | + settings.max_param_length = max_param_length |
| 33 | + settings.dangerous_patterns = dangerous_patterns |
| 34 | + settings.experimental_rust_validation_middleware_enabled = False |
| 35 | + settings.environment = "production" |
| 36 | + middleware = ValidationMiddleware(app=None) |
| 37 | + middleware.dangerous_patterns = [re.compile(pattern) for pattern in dangerous_patterns] |
| 38 | + |
| 39 | + def _run(data: Any) -> None: |
| 40 | + middleware._validate_json_data(data) |
| 41 | + |
| 42 | + return _run |
| 43 | + |
| 44 | + |
| 45 | +def _build_rust_validator(max_param_length: int, dangerous_patterns: list[str]) -> Callable[[Any], None]: |
| 46 | + sidecar = _ensure_sidecar_installed() |
| 47 | + settings.max_param_length = max_param_length |
| 48 | + settings.dangerous_patterns = dangerous_patterns |
| 49 | + settings.environment = "production" |
| 50 | + |
| 51 | + def _run(data: Any) -> None: |
| 52 | + result = sidecar.validate_json_data(data, max_param_length, dangerous_patterns) |
| 53 | + if result is None: |
| 54 | + return |
| 55 | + key, error_type = result |
| 56 | + if error_type == "max_length": |
| 57 | + raise HTTPException(status_code=422, detail=f"Parameter {key} exceeds maximum length") |
| 58 | + raise HTTPException(status_code=422, detail=f"Parameter {key} contains dangerous characters") |
| 59 | + |
| 60 | + return _run |
| 61 | + |
| 62 | + |
| 63 | +def _measure(label: str, fn: Callable[[Any], None], payload: Any, iterations: int) -> tuple[float, float]: |
| 64 | + samples = [] |
| 65 | + for _ in range(iterations): |
| 66 | + started = time.perf_counter_ns() |
| 67 | + try: |
| 68 | + fn(payload) |
| 69 | + except HTTPException: |
| 70 | + pass |
| 71 | + samples.append(time.perf_counter_ns() - started) |
| 72 | + |
| 73 | + median_ms = statistics.median(samples) / 1_000_000 |
| 74 | + p95_ms = statistics.quantiles(samples, n=100)[94] / 1_000_000 |
| 75 | + print(f"{label}: median={median_ms:.3f}ms p95={p95_ms:.3f}ms") |
| 76 | + return median_ms, p95_ms |
| 77 | + |
| 78 | + |
| 79 | +def _assert_parity(python_fn: Callable[[Any], None], rust_fn: Callable[[Any], None], payloads: list[Any]) -> None: |
| 80 | + for payload in payloads: |
| 81 | + python_error = None |
| 82 | + rust_error = None |
| 83 | + |
| 84 | + try: |
| 85 | + python_fn(payload) |
| 86 | + except HTTPException as exc: |
| 87 | + python_error = (exc.status_code, exc.detail) |
| 88 | + |
| 89 | + try: |
| 90 | + rust_fn(payload) |
| 91 | + except HTTPException as exc: |
| 92 | + rust_error = (exc.status_code, exc.detail) |
| 93 | + |
| 94 | + if python_error != rust_error: |
| 95 | + raise AssertionError(f"Parity mismatch for payload {payload!r}: python={python_error!r} rust={rust_error!r}") |
| 96 | + |
| 97 | + |
| 98 | +def main() -> None: |
| 99 | + max_param_length = 1024 |
| 100 | + dangerous_patterns = [r"[;&|`$(){}\[\]<>]", r"\.\.[\\/]", r"[\x00-\x1f\x7f-\x9f]"] |
| 101 | + |
| 102 | + python_fn = _build_python_validator(max_param_length, dangerous_patterns) |
| 103 | + rust_fn = _build_rust_validator(max_param_length, dangerous_patterns) |
| 104 | + |
| 105 | + parity_payloads = [ |
| 106 | + {"name": "safe", "nested": {"description": "still safe"}}, |
| 107 | + {"prompt": "<script>alert(1)</script>"}, |
| 108 | + {"outer": {"inner": "a" * 2048}}, |
| 109 | + ] |
| 110 | + _assert_parity(python_fn, rust_fn, parity_payloads) |
| 111 | + |
| 112 | + scenarios = [ |
| 113 | + ( |
| 114 | + "nested_safe", |
| 115 | + { |
| 116 | + "tool": { |
| 117 | + "name": "safe-tool", |
| 118 | + "description": "ok" * 32, |
| 119 | + "metadata": [{"field": "value" * 8} for _ in range(256)], |
| 120 | + } |
| 121 | + }, |
| 122 | + 400, |
| 123 | + ), |
| 124 | + ( |
| 125 | + "deep_nested", |
| 126 | + {"batch": [{"payload": {"name": f"item-{index}", "content": ("alpha-beta-gamma-" * 16)}} for index in range(512)]}, |
| 127 | + 250, |
| 128 | + ), |
| 129 | + ( |
| 130 | + "dangerous_string", |
| 131 | + {"batch": [{"payload": {"name": f"item-{index}", "content": "safe-content"}} for index in range(511)] + [{"payload": {"name": "bad", "content": "<script>alert(1)</script>"}}]}, |
| 132 | + 250, |
| 133 | + ), |
| 134 | + ] |
| 135 | + |
| 136 | + for name, payload, iterations in scenarios: |
| 137 | + print(f"\n{name} ({iterations} iterations)") |
| 138 | + python_median, _ = _measure("python", python_fn, payload, iterations) |
| 139 | + rust_median, _ = _measure("rust", rust_fn, payload, iterations) |
| 140 | + print(f"speedup={python_median / rust_median:.2f}x") |
| 141 | + |
| 142 | + |
| 143 | +if __name__ == "__main__": |
| 144 | + main() |
0 commit comments