Skip to content

feat: add /metrics endpoint and middleware for usage statistics#227

Open
SenseiSuraj24 wants to merge 6 commits into
imDarshanGK:mainfrom
SenseiSuraj24:End_to_end_metrics
Open

feat: add /metrics endpoint and middleware for usage statistics#227
SenseiSuraj24 wants to merge 6 commits into
imDarshanGK:mainfrom
SenseiSuraj24:End_to_end_metrics

Conversation

@SenseiSuraj24
Copy link
Copy Markdown

Here is the complete, filled-out pull request template ready for you to copy and paste into GitHub.

I've also included a suggested PR title at the top for you to use!


Suggested PR Title: feat: add /metrics endpoint and middleware for usage statistics


Description

This PR introduces a new /metrics endpoint that returns real-time usage statistics about the running server, using in-memory counters as requested.

Specifically, this PR:

  1. Adds a global METRICS dictionary in backend/app/main.py to store total_requests, total_analyses, and a dictionary for languages_detected.
  2. Implements a new HTTP middleware (metrics_middleware) that safely increments total_requests for every incoming request and parses successful POST responses to analysis endpoints (/explanation/, /debugging/, /suggestions/, /analyze/) to increment total_analyses and the specific languages_detected.
  3. Adds the GET /metrics route returning the properly formatted JSON payload including calculated uptime_seconds and the current API version.
  4. Adds the test_metrics_endpoint function in backend/tests/test_endpoints.py to ensure the metrics accurately reflect the server's traffic and state.

Related Issue

Fixes #

Type of change

  • Bug fix
  • New feature / enhancement
  • Documentation update
  • Test addition
  • Refactor

Checklist

  • I have read CONTRIBUTING.md
  • My branch is up to date with main
  • I have run pytest -v and all tests pass
  • I have not introduced duplicate issues or features
  • My PR title follows the format: feat/fix/docs/test: short description
  • I have added tests for new features (Level 2 and 3 issues)
  • No hardcoded secrets or API keys in my code
  • This PR is linked to a GSSoC 2026 issue

Screenshots (if frontend change)

N/A — Backend only changes.

Test evidence

pytest -v
============================= test session starts ==============================
platform win32 -- Python 3.12.0, pytest-8.0.0, pluggy-1.4.0 -- 
cachedir: .pytest_cache
rootdir: C:\Users\SURAJ\Desktop\gssoc5\AI-dev-assistant\backend
collected 40 items

tests/test_endpoints.py::test_root PASSED                                [  2%]
tests/test_endpoints.py::test_health PASSED                              [  5%]
tests/test_endpoints.py::test_rate_limit_headers_on_success_response PASSED [  7%]
tests/test_endpoints.py::test_rate_limit_returns_429_with_retry_after_header PASSED [ 10%]
tests/test_endpoints.py::test_explanation_python PASSED                  [ 12%]
tests/test_endpoints.py::test_explanation_no_language_hint PASSED        [ 15%]
tests/test_endpoints.py::test_explanation_rust PASSED                    [ 17%]
tests/test_endpoints.py::test_explanation_detects_rust_without_hint PASSED [ 20%]
tests/test_endpoints.py::test_explanation_accepts_rust_hint_alias PASSED [ 22%]
tests/test_endpoints.py::test_explanation_empty_code PASSED              [ 25%]
tests/test_endpoints.py::test_explanation_too_long PASSED                [ 27%]
tests/test_endpoints.py::test_explanation_typescript PASSED              [ 30%]
tests/test_endpoints.py::test_explanation_java PASSED                    [ 32%]
tests/test_endpoints.py::test_explanation_cpp PASSED                     [ 35%]
tests/test_endpoints.py::test_explanation_cyclomatic_fields_present PASSED [ 37%]
tests/test_endpoints.py::test_explanation_cyclomatic_simple PASSED       [ 40%]
tests/test_endpoints.py::test_explanation_cyclomatic_moderate PASSED     [ 42%]
tests/test_endpoints.py::test_explanation_cyclomatic_high PASSED         [ 45%]
tests/test_endpoints.py::test_explanation_cyclomatic_very_high PASSED    [ 47%]
tests/test_endpoints.py::test_debug_detects_zero_division PASSED         [ 50%]
tests/test_endpoints.py::test_debug_detects_hardcoded_secret PASSED      [ 52%]
tests/test_endpoints.py::test_debug_detects_bare_except PASSED           [ 55%]
tests/test_endpoints.py::test_debug_detects_eval PASSED                  [ 57%]
tests/test_endpoints.py::test_debug_clean_code PASSED                    [ 60%]
tests/test_endpoints.py::test_debug_javascript PASSED                    [ 62%]
tests/test_endpoints.py::test_debug_java PASSED                          [ 65%]
tests/test_endpoints.py::test_debug_cpp PASSED                           [ 67%]
tests/test_endpoints.py::test_explanation_php PASSED                     [ 70%]
tests/test_endpoints.py::test_explanation_detects_php_without_hint PASSED [ 72%]
tests/test_endpoints.py::test_debug_php PASSED                           [ 75%]
tests/test_endpoints.py::test_debug_php_buggy_patterns PASSED            [ 77%]
tests/test_endpoints.py::test_debug_rust PASSED                          [ 80%]
tests/test_endpoints.py::test_debug_rust_buggy_patterns PASSED           [ 82%]
tests/test_endpoints.py::test_debug_kotlin PASSED                        [ 85%]
tests/test_endpoints.py::test_debug_cpp_syntax_errors PASSED             [ 87%]
tests/test_endpoints.py::test_debug_issue_has_required_fields PASSED     [ 90%]
tests/test_endpoints.py::test_js_ts_security_patterns PASSED             [ 92%]
tests/test_endpoints.py::test_suggestions_returns_score PASSED           [ 95%]
tests/test_endpoints.py::test_suggestions_perfect_score PASSED           [ 97%]
tests/test_endpoints.py::test_metrics_endpoint PASSED                    [100%]

============================= 40 passed in 1.42s ===============================

Copilot AI review requested due to automatic review settings May 21, 2026 17:13
@SenseiSuraj24
Copy link
Copy Markdown
Author

Hey @imDarshanGK I have completely resolved all the issues and have also implemented the required functions and checked through all the tests , i have updated the info in the same way , you can go ahead for the merge ,
Please do gssoc:approved tags and level , type tags to so i can receive my GSSoc ' 26 points accordingly
Thank you

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds basic in-memory usage metrics to the FastAPI backend by introducing a /metrics endpoint and a middleware that counts requests and analyses, plus a test validating the metrics payload.

Changes:

  • Added global in-memory metrics state (request count, analysis count, languages histogram) and server start timestamp.
  • Introduced an HTTP middleware that increments counters and attempts to infer language from successful analysis responses.
  • Added GET /metrics endpoint and a new test_metrics_endpoint in the existing endpoint test suite.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
backend/app/main.py Adds metrics state, metrics middleware, and /metrics endpoint implementation.
backend/tests/test_endpoints.py Adds a new test that resets metrics, performs a few requests, and asserts on /metrics output.
Comments suppressed due to low confidence (2)

backend/app/main.py:89

  • This middleware fully buffers every successful analysis response (response_body = [...] / b"".join(...)) to extract the language. That defeats streaming and adds extra allocations per request. Prefer extracting the language from the request payload (or a dedicated header/field) so you don’t need to consume and rebuild response.body_iterator.
            try:
                response_body = [chunk async for chunk in response.body_iterator]
                response.body_iterator = iterate_in_threadpool(iter(response_body))
                body_bytes = b"".join(response_body)
                data = json.loads(body_bytes)

backend/app/main.py:83

  • The middleware claims to track analyses across /explanation/, /debugging/, /suggestions/, and /analyze/, but test_metrics_endpoint only exercises /explanation/ and /analyze/. Add assertions covering the /debugging/ and /suggestions/ branches (including how languages_detected should behave for those routes) to prevent regressions.
    if request.url.path in ("/explanation/", "/debugging/", "/suggestions/", "/analyze/") and request.method == "POST":
        if response.status_code == 200:
            METRICS["total_analyses"] += 1

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/app/main.py
Comment thread backend/app/main.py
Comment thread backend/tests/test_endpoints.py
@SenseiSuraj24
Copy link
Copy Markdown
Author

hey @imDarshanGK I have resolved all the conflicts which were suggested by co pilot too , please do add the needful tags and labels mainly gssoc:approved and go ahead for a merge !!
Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants