Skip to content

Issue/502 request context cleanup#503

Merged
armanist merged 3 commits intosoftberg:masterfrom
armanist:issue/502-request-context-cleanup
May 5, 2026
Merged

Issue/502 request context cleanup#503
armanist merged 3 commits intosoftberg:masterfrom
armanist:issue/502-request-context-cleanup

Conversation

@armanist
Copy link
Copy Markdown
Member

@armanist armanist commented May 5, 2026

Closes #502

Summary by CodeRabbit

  • Bug Fixes

    • Authentication middleware now properly halts request processing when authorization or authentication checks fail, preventing unintended progression to subsequent middleware handlers.
  • Tests

    • Enhanced test coverage to validate comprehensive cleanup of request context data and response states following request processing completion.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 5, 2026

Warning

Rate limit exceeded

@armanist has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 48 minutes and 50 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6c614c65-318d-4250-83e3-e711766aa916

📥 Commits

Reviewing files that changed from the base of the PR and between e73707a and b2ef619.

📒 Files selected for processing (2)
  • src/App/Traits/WebAppTrait.php
  • tests/Unit/App/Adapters/WebAppAdapterTest.php
📝 Walkthrough

Walkthrough

The PR implements post-response request-context cleanup by adding a cleanupRequestContext() method to WebAppTrait that clears matched routes and flushes request/response state after sending responses. Auth middleware templates are fixed to return early on authentication failures, and unit tests are enhanced to validate cleanup behavior.

Changes

Request-Context Lifecycle Cleanup

Layer / File(s) Summary
Cleanup Implementation
src/App/Traits/WebAppTrait.php
New cleanupRequestContext() method clears request()->matchedRoute, flushes request state via request()->flush(), and flushes response state via response()->flush(). Called immediately after $response->send() in sendResponse().
Middleware Control Flow
src/Module/Templates/DemoApi/src/Middlewares/Auth.php.tpl, src/Module/Templates/DemoWeb/src/Middlewares/Auth.php.tpl
Both auth middleware templates now return early on authentication failures (return error/redirect) instead of continuing to $next($request), ensuring proper cleanup execution during response handling.
Cleanup Validation
tests/Unit/App/Adapters/WebAppAdapterTest.php
Three test methods now assert post-start() cleanup state: getMatchedRoute() and getUri() are null, response body and headers are empty arrays, and status code is 200.

Sequence Diagram

sequenceDiagram
    participant App as WebApp Lifecycle
    participant Response as Response Handler
    participant Request as Request State
    
    App->>Response: send response
    Response->>Response: emit headers & body
    activate Response
    Response-->>App: send complete
    deactivate Response
    
    App->>Request: clearMatchedRoute()
    Request-->>App: ✓
    
    App->>Request: flush()
    Request-->>App: clear headers, body, params
    
    App->>Response: flush()
    Response-->>App: clear body, headers, status
    
    Note over App,Response: Request-scoped state cleaned<br/>App safe for next request
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 A tidy request hops away,
Its matched route brushed clean each day,
Headers flushed, state cleared true,
App resets—fresh as morning dew! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Issue/502 request context cleanup' clearly and concisely summarizes the main change: implementing post-response request-context cleanup as specified in issue #502.
Linked Issues check ✅ Passed The PR implements the core cleanup lifecycle requirements: cleanupRequestContext() clears matched route, flushes request state, and flushes response state after sendResponse(). Auth middleware templates correctly return responses. Tests verify cleanup side effects.
Out of Scope Changes check ✅ Passed All changes align with issue #502 scope: WebAppTrait cleanup method, Auth middleware return statements, and WebAppAdapter tests validating cleanup. No unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 5, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.87%. Comparing base (c476902) to head (b2ef619).

Additional details and impacted files
@@            Coverage Diff            @@
##             master     #503   +/-   ##
=========================================
  Coverage     90.87%   90.87%           
- Complexity     2926     2927    +1     
=========================================
  Files           255      255           
  Lines          7703     7708    +5     
=========================================
+ Hits           7000     7005    +5     
  Misses          703      703           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/App/Traits/WebAppTrait.php (1)

142-147: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Ensure cleanup always runs on exception paths.

If handleCors() or $response->send() throws, cleanupRequestContext() is skipped, which can leak request-scoped state across consecutive in-process requests.

Proposed fix
 private function sendResponse(Response $response): void
 {
-    $this->handleCors($response);
-    $response->send();
-    $this->cleanupRequestContext();
+    try {
+        $this->handleCors($response);
+        $response->send();
+    } finally {
+        $this->cleanupRequestContext();
+    }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/App/Traits/WebAppTrait.php` around lines 142 - 147, The sendResponse
method can skip cleanupRequestContext if handleCors() or Response::send()
throws; update sendResponse to ensure cleanupRequestContext() always runs by
wrapping the calls to $this->handleCors($response) and $response->send() in a
try/finally (or try/catch/finally) so cleanupRequestContext() is invoked in the
finally block, and optionally rethrow any caught exception after cleanup.
🧹 Nitpick comments (1)
tests/Unit/App/Adapters/WebAppAdapterTest.php (1)

23-69: ⚡ Quick win

Add one exception-path cleanup test.

Consider adding a test where response sending fails (or CORS setup throws) and then assert request/response context is still cleaned. That locks in the lifecycle guarantee under failure paths too.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/Unit/App/Adapters/WebAppAdapterTest.php` around lines 23 - 69, Add a
new test (e.g., testWebAppAdapterCleansUpOnException) that simulates an
exception during the adapter lifecycle (for example mock/stub the component that
sends the response or the CORS setup to throw when response()->send() or
cors()->setup() is invoked) then call $this->webAppAdapter->start() wrapped to
catch the exception and finally assert the same cleanup guarantees as the other
tests: request() has no matched route and no URI, response()->all() and
response()->allHeaders() are empty, and response()->getStatusCode() is 200; this
ensures webAppAdapter->start() cleans request/response context even on failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/App/Traits/WebAppTrait.php`:
- Around line 142-147: The sendResponse method can skip cleanupRequestContext if
handleCors() or Response::send() throws; update sendResponse to ensure
cleanupRequestContext() always runs by wrapping the calls to
$this->handleCors($response) and $response->send() in a try/finally (or
try/catch/finally) so cleanupRequestContext() is invoked in the finally block,
and optionally rethrow any caught exception after cleanup.

---

Nitpick comments:
In `@tests/Unit/App/Adapters/WebAppAdapterTest.php`:
- Around line 23-69: Add a new test (e.g., testWebAppAdapterCleansUpOnException)
that simulates an exception during the adapter lifecycle (for example mock/stub
the component that sends the response or the CORS setup to throw when
response()->send() or cors()->setup() is invoked) then call
$this->webAppAdapter->start() wrapped to catch the exception and finally assert
the same cleanup guarantees as the other tests: request() has no matched route
and no URI, response()->all() and response()->allHeaders() are empty, and
response()->getStatusCode() is 200; this ensures webAppAdapter->start() cleans
request/response context even on failure.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6c73b4dc-2281-4265-9a07-92732ee58d24

📥 Commits

Reviewing files that changed from the base of the PR and between c476902 and e73707a.

📒 Files selected for processing (4)
  • src/App/Traits/WebAppTrait.php
  • src/Module/Templates/DemoApi/src/Middlewares/Auth.php.tpl
  • src/Module/Templates/DemoWeb/src/Middlewares/Auth.php.tpl
  • tests/Unit/App/Adapters/WebAppAdapterTest.php

@armanist armanist requested a review from andrey-smaelov May 5, 2026 16:24
@armanist armanist added this to the 3.0.0 milestone May 5, 2026
@armanist armanist merged commit f296867 into softberg:master May 5, 2026
7 checks passed
@armanist armanist deleted the issue/502-request-context-cleanup branch May 5, 2026 16:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Post-response request-context cleanup

2 participants