Skip to content

Split API endpoints by content type #6931

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Mar 27, 2025

Conversation

jeandemeusy
Copy link
Contributor

@jeandemeusy jeandemeusy commented Mar 18, 2025

Allows the metric endpoint to return response properly when the content type is en-forced to text/plain when doing the query.
This fixes SwaggerUI not rendering the metrics.

@jeandemeusy jeandemeusy self-assigned this Mar 18, 2025
Copy link
Contributor

coderabbitai bot commented Mar 18, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new nested router for the /metrics endpoint by updating the REST API. The new router employs several middleware layers such as authentication, WebSocket support, tracing, CORS, request recording, compression, and header validation. The previous /node/metrics route is removed. Additionally, method signatures in the Python SDK have been updated to provide better control over URL construction for API calls, and new tests have been added to verify endpoint header behavior. The package version has also been bumped accordingly.

Changes

File(s) Change Summary
hoprd/rest-api/src/lib.rs Introduces a nested router for /metrics with multiple middleware layers (authentication, WebSocket, tracing, CORS, etc.), removes the previous /node/metrics endpoint, and updates state management via cloning.
hoprd/rest-api/Cargo.toml Updates the package version of hoprd-api from "3.11.1" to "3.11.2".
sdk/python/api/hopr.py Updates the __call and __call_api method signatures in HoprdAPI by adding the use_api_path parameter. Adjusts the metrics endpoint URL construction accordingly.
tests/test_rest_api.py Adds two asynchronous tests to verify that the metrics and info endpoints respond correctly to different Accept header values.
hoprd/rest-api/README.md Adds a new line to the README file without altering existing content.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant AuthMiddleware
    participant WebSocketMiddleware
    participant ServiceBuilder
    participant APIHandler

    Client->>Router: Request `/metrics`
    Router->>AuthMiddleware: Apply Authentication
    AuthMiddleware->>Router: Return authenticated request
    Router->>WebSocketMiddleware: Check WebSocket upgrade
    WebSocketMiddleware->>Router: Forward request
    Router->>ServiceBuilder: Invoke tracing, CORS, etc.
    ServiceBuilder->>APIHandler: Process request
    APIHandler->>Router: Return response
    Router->>Client: Deliver final response
Loading

Possibly related PRs

Suggested labels

component:api, crate:hopr-lib

Suggested reviewers

  • Teebor-Choka
  • tolbrino

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 962ad05 and 0c88a60.

📒 Files selected for processing (1)
  • hoprd/rest-api/README.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • hoprd/rest-api/README.md
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: hoprd / docker
  • GitHub Check: hopli / docker
  • GitHub Check: Docs / Rust docs
  • GitHub Check: tests-unit
  • GitHub Check: tests-smoke-websocket
  • GitHub Check: tests-unit-nightly
  • GitHub Check: tests-smart-contracts
  • GitHub Check: Linter

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@NumberFour8 NumberFour8 left a comment

Choose a reason for hiding this comment

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

Crate version bump missing.

@jeandemeusy jeandemeusy enabled auto-merge March 18, 2025 13:59
@jeandemeusy jeandemeusy disabled auto-merge March 18, 2025 13:59
@github-actions github-actions bot added the dependencies Pull requests that update a dependency file label Mar 18, 2025
Copy link
Contributor

@Teebor-Choka Teebor-Choka left a comment

Choose a reason for hiding this comment

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

As mentioned by @tolbrino in the chat, please, leave the layer in place, but create an exception with test/plain for the metrics endpoint.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
hoprd/rest-api/src/lib.rs (1)

265-292: Implementation of a separate router for metrics route with text/plain content type looks good.

This change correctly implements a dedicated router for the /node/metrics endpoint that accepts text/plain content type, which aligns with the PR objective of removing content type validation constraints. The metrics endpoint now properly accepts plain text data instead of requiring JSON format.

While the implementation is correct, consider extracting the common middleware configuration patterns between this router and the main router to reduce code duplication. This would improve maintainability for future changes.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc350c3 and 465cfea.

📒 Files selected for processing (1)
  • hoprd/rest-api/src/lib.rs (2 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
hoprd/rest-api/src/lib.rs (1)
hoprd/rest-api/src/node.rs (1) (1)
  • metrics (265-270)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: hoprd / docker
  • GitHub Check: hopli / docker
  • GitHub Check: Docs / Rust docs
  • GitHub Check: tests-smoke-websocket
  • GitHub Check: tests-smart-contracts
  • GitHub Check: tests-unit-nightly
  • GitHub Check: Linter
  • GitHub Check: tests-unit
🔇 Additional comments (2)
hoprd/rest-api/src/lib.rs (2)

349-350: Good use of cloning the inner state.

Properly cloning the inner_state when passing it to the middleware function ensures that each middleware gets its own copy of the state, preventing any potential issues with shared mutable state.


353-366: Consistent middleware configuration for the main router.

The middleware stack for the main router is properly configured to maintain JSON validation, which provides a clean separation of concerns between the metrics endpoint (plain text) and all other endpoints (JSON).

@jeandemeusy jeandemeusy changed the title Remove content type validation layer in the API Split API endpoints by content type Mar 19, 2025
@tolbrino tolbrino added this to the 3.0.0 milestone Mar 20, 2025
Copy link
Contributor

@tolbrino tolbrino left a comment

Choose a reason for hiding this comment

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

Would be nice to have some test verify this.

@github-actions github-actions bot added the testing Related to tests label Mar 21, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
tests/test_rest_api.py (4)

41-53: Consider optimizing the test function to reuse HTTP session.

The test creates three separate ClientSession instances, which is inefficient. Consider reusing a single session for all requests in this test.

Here's a more efficient implementation:

 async def test_metric_endpoint_accepts_plain_text_header(peer: str, swarm7: dict[str, Node]):
     url = f"http://{swarm7[peer].host_addr}:{swarm7[peer].api_port}/metrics"
     headers = {"X-Auth-Token": swarm7[peer].api_token}
 
-    async with aiohttp.ClientSession(headers=headers) as s:
-        assert (await s.get(url)).status == 200
-
-    async with aiohttp.ClientSession(headers=headers+{"accept": "text/plain"}) as s:
-        assert (await s.get(url)).status == 200
-
-    async with aiohttp.ClientSession(headers=headers+{"accept": "application/json"}) as s:
-        assert (await s.get(url)).status == 406
+    async with aiohttp.ClientSession() as s:
+        # Test with default headers (no accept header)
+        assert (await s.get(url, headers=headers)).status == 200
+        
+        # Test with text/plain accept header
+        plain_headers = {**headers, "accept": "text/plain"}
+        assert (await s.get(url, headers=plain_headers)).status == 200
+        
+        # Test with application/json accept header
+        json_headers = {**headers, "accept": "application/json"}
+        assert (await s.get(url, headers=json_headers)).status == 406

41-53: Enhance test assertions with descriptive messages.

The assertions would be more helpful during debugging if they included descriptive messages explaining what's being tested.

Consider adding descriptive messages:

 async def test_metric_endpoint_accepts_plain_text_header(peer: str, swarm7: dict[str, Node]):
     url = f"http://{swarm7[peer].host_addr}:{swarm7[peer].api_port}/metrics"
     headers = {"X-Auth-Token": swarm7[peer].api_token}

     async with aiohttp.ClientSession() as s:
-        assert (await s.get(url, headers=headers)).status == 200
+        response = await s.get(url, headers=headers)
+        assert response.status == 200, f"Expected 200 OK for default request, got {response.status}"
         
-        assert (await s.get(url, headers={**headers, "accept": "text/plain"})).status == 200
+        response = await s.get(url, headers={**headers, "accept": "text/plain"})
+        assert response.status == 200, f"Expected 200 OK for text/plain request, got {response.status}"
         
-        assert (await s.get(url, headers={**headers, "accept": "application/json"})).status == 406
+        response = await s.get(url, headers={**headers, "accept": "application/json"})
+        assert response.status == 406, f"Expected 406 Not Acceptable for application/json request, got {response.status}"

41-53: Consider validating response content type, not just status code.

The test only checks status codes but doesn't verify that the response content type matches the requested format. This would make the test more robust.

Add content type verification:

 async def test_metric_endpoint_accepts_plain_text_header(peer: str, swarm7: dict[str, Node]):
     url = f"http://{swarm7[peer].host_addr}:{swarm7[peer].api_port}/metrics"
     headers = {"X-Auth-Token": swarm7[peer].api_token}

     async with aiohttp.ClientSession() as s:
-        assert (await s.get(url, headers={**headers, "accept": "text/plain"})).status == 200
+        response = await s.get(url, headers={**headers, "accept": "text/plain"})
+        assert response.status == 200, "Expected 200 OK for text/plain request"
+        content_type = response.headers.get('Content-Type', '')
+        assert 'text/plain' in content_type, f"Expected text/plain content type, got {content_type}"

53-53: Add a newline at the end of the file.

The file is missing a newline at the end, which can cause issues with some linters and version control systems.

Add an empty line at the end of the file.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f8cfbda and 927231c.

📒 Files selected for processing (1)
  • tests/test_rest_api.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: hoprd / docker
  • GitHub Check: hopli / docker
  • GitHub Check: tests-unit
  • GitHub Check: Docs / Rust docs
  • GitHub Check: tests-unit-nightly
  • GitHub Check: tests-smoke-websocket
  • GitHub Check: Linter
  • GitHub Check: tests-smart-contracts

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/test_rest_api.py (2)

48-54: Suggestion: Consider reusing the ClientSession

For improved efficiency, consider reusing the same ClientSession for all requests within the test function instead of creating a new one for each request.

-    async with aiohttp.ClientSession(headers=headers) as s:
-        assert (await s.get(url)).status == 200
-
-    headers["accept"] = "text/plain"
-    async with aiohttp.ClientSession(headers=headers) as s:
-        assert (await s.get(url)).status == 200
-
-    headers["accept"] = "application/json"
-    async with aiohttp.ClientSession(headers=headers) as s:
-        assert (await s.get(url)).status == 406
+    async with aiohttp.ClientSession() as s:
+        # Test with default headers
+        assert (await s.get(url, headers=headers)).status == 200
+        
+        # Test with text/plain accept header
+        headers_plain = {**headers, "accept": "text/plain"}
+        assert (await s.get(url, headers=headers_plain)).status == 200
+        
+        # Test with application/json accept header
+        headers_json = {**headers, "accept": "application/json"}
+        assert (await s.get(url, headers=headers_json)).status == 406

66-72: Apply the same session reuse pattern to this test

For consistency, consider applying the same ClientSession reuse pattern to this test function as well.

-    headers["accept"] = "text/plain"
-    async with aiohttp.ClientSession(headers=headers) as s:
-        assert (await s.get(url)).status == 406
-
-    headers["accept"] = "application/json"
-    async with aiohttp.ClientSession(headers=headers) as s:
-        assert (await s.get(url)).status == 200
+    async with aiohttp.ClientSession() as s:
+        # Test with default headers
+        assert (await s.get(url, headers=headers)).status == 200
+        
+        # Test with text/plain accept header
+        headers_plain = {**headers, "accept": "text/plain"}
+        assert (await s.get(url, headers=headers_plain)).status == 406
+        
+        # Test with application/json accept header
+        headers_json = {**headers, "accept": "application/json"}
+        assert (await s.get(url, headers=headers_json)).status == 200
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 927231c and ff847a7.

📒 Files selected for processing (1)
  • tests/test_rest_api.py (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
tests/test_rest_api.py (2)
tests/conftest.py (2) (2)
  • nodes_with_auth (59-61)
  • swarm7 (79-88)
sdk/python/localcluster/node.py (1) (1)
  • Node (35-266)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: tests-smoke-websocket
  • GitHub Check: tests-smart-contracts
  • GitHub Check: tests-unit
  • GitHub Check: tests-unit-nightly
  • GitHub Check: hopli / docker
  • GitHub Check: hoprd / docker
  • GitHub Check: Docs / Rust docs
  • GitHub Check: Linter
🔇 Additional comments (2)
tests/test_rest_api.py (2)

39-55: Test for metrics endpoint looks good!

This test correctly verifies that the metrics endpoint:

  1. Returns 200 with default headers
  2. Returns 200 when explicitly requesting text/plain content
  3. Returns 406 (Not Acceptable) when requesting application/json content

This aligns with the PR objective of enforcing text/plain for the metrics endpoint.


57-72: Test for info endpoint looks good!

This test correctly verifies the opposite behavior for the info endpoint:

  1. Returns 200 with default headers
  2. Returns 406 (Not Acceptable) when requesting text/plain content
  3. Returns 200 when requesting application/json content

This complements the metrics endpoint test and provides good coverage of the content type enforcement changes.

@jeandemeusy jeandemeusy enabled auto-merge March 24, 2025 14:35
@Teebor-Choka Teebor-Choka dismissed their stale review March 24, 2025 16:01

No longer relevant.

@jeandemeusy jeandemeusy added this pull request to the merge queue Mar 24, 2025
@jeandemeusy jeandemeusy removed this pull request from the merge queue due to a manual request Mar 24, 2025
@jeandemeusy jeandemeusy merged commit 4655d98 into master Mar 27, 2025
29 of 30 checks passed
@jeandemeusy jeandemeusy deleted the jean/allow-any-format-in-curl-request branch March 27, 2025 15:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
crate:hoprd-api dependencies Pull requests that update a dependency file testing Related to tests
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Metrics endpoint does not work with header text/plain
4 participants