Skip to content

chore: payload size middleware performance improvement - #4318

Merged
atzoum merged 1 commit into
developfrom
chore.payloadSizeMiddleware
May 15, 2025
Merged

atzoum merged 1 commit into
developfrom
chore.payloadSizeMiddleware

Conversation

@atzoum

@atzoum atzoum commented May 14, 2025 •

Copy link
Copy Markdown
Contributor

Description

Instead of performing JSON.stringify we are using precalculated raw payload sizes for capturing metrics:

  • transformer_http_request_size: using ctx.request.rawBody provided by koa-bodyparser
  • transformer_http_response_size: using ctx.response.length provided by koa

This has a positive impact on server's performance and cpu utilization, especially while dealing with larger payloads

@atzoum
atzoum requested a review from sivashanmukh as a code owner May 14, 2025 10:57
@atzoum
atzoum requested a review from a team May 14, 2025 10:57
@coderabbitai

coderabbitai Bot commented May 14, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Refactor
    • Unified middleware registration by introducing functions that register middleware directly on the app instance.
    • Updated request and response size measurement methods for improved accuracy.
  • Tests
    • Enhanced middleware tests to use integration-style testing with real HTTP requests for more realistic validation.

Summary by CodeRabbit

  • Refactor
    • Streamlined middleware registration for request and response size tracking, now directly attaching middleware to the app instance.
    • Unified the way middleware is added, improving consistency in setup.
  • Tests
    • Updated tests to use real HTTP requests and Koa app instances for more accurate validation of request and response size tracking.

Walkthrough

This update refactors middleware registration in a Koa application, transitioning from returning middleware functions to directly registering them on the app instance. The request and response size tracking logic is updated to use raw body data and response length. Corresponding tests are restructured to use real HTTP requests via Supertest for more accurate validation.

Changes

File(s) Change Summary
src/index.ts Simplified the bodyParser middleware usage by consolidating its configuration into a single-line object literal.
src/middleware.js Refactored middleware from returning functions to directly registering on the Koa app; updated size tracking logic; added addStatMiddleware.
src/middleware.test.js Rewrote tests to use real Koa app instances and Supertest for HTTP requests, ensuring accurate measurement and assertions.

Suggestions for Improvements

  • Consider adding TypeScript typings for middleware registration functions to enhance maintainability and clarity.
  • Include more comprehensive error handling in middleware, especially for edge cases involving malformed requests or missing middleware dependencies.
  • Expand test coverage to include scenarios with large payloads and invalid JSON to ensure robustness under various conditions.
  • Document the new middleware registration pattern in project documentation for consistency among contributors.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between cb529d17a624069486d61690d464dc4c26e9717b and 813c2c1.

📒 Files selected for processing (3)
  • src/index.ts (1 hunks)
  • src/middleware.js (2 hunks)
  • src/middleware.test.js (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/index.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/middleware.js
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

  • src/middleware.test.js
🧬 Code Graph Analysis (1)
src/middleware.test.js (1)
src/middleware.js (2)
  • require (3-3)
  • stats (4-4)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (7)
src/middleware.test.js (7)

1-3: Good use of test dependencies for integration testing

Using Koa, koa-bodyparser, and supertest together creates a more realistic test environment that better simulates actual HTTP requests and responses, which is a significant improvement over manual context mocking.


93-98: Good test setup using actual middleware chain

Setting up a complete middleware stack with bodyParser and the request size middleware creates a more realistic test environment. This is a good practice for integration testing.


100-107: Well-structured HTTP request and response validation

Using supertest to make real HTTP requests and validate responses is a good approach. The assertions for status code and response body ensure the middleware doesn't interfere with normal request processing.


122-130: Good edge case testing

Testing behavior with missing request and response bodies is important for ensuring the middleware handles all scenarios correctly. The structure of this test case is clean and follows good practices.


145-156: Good test for empty objects

Testing with empty objects is valuable for verifying edge cases. The pre-calculation of expected sizes is appropriate and matches the test's intent.


158-176: Complete end-to-end verification

This test section properly verifies both the HTTP interaction and the metric recording. The expectations for the histogram calls are specific and validate both the size values and the associated metadata.


88-91:

Details

❌ Incorrect review comment

Potential inconsistency with PR objective

The PR objective mentions replacing JSON.stringify with ctx.request.rawBody and ctx.response.length, but the tests still calculate expected sizes using Buffer.byteLength(JSON.stringify(body)). Consider updating the test expectations to align with how the middleware actually calculates sizes now.


🏁 Script executed:

#!/bin/bash
# Verify how the middleware implementation actually calculates sizes
rg -A 10 "addRequestSizeMiddleware" src/middleware.js

Length of output: 406


🏁 Script executed:

#!/bin/bash
echo "---- Middleware Code ----"
rg -A 30 "function addRequestSizeMiddleware" src/middleware.js || true

echo "---- Test Code (first 200 lines) ----"
sed -n '1,200p' src/middleware.test.js || true

echo "---- JSON.stringify usages in Tests ----"
rg -n "JSON.stringify" -n src/middleware.test.js || true

Length of output: 6431


Test expectations already align with middleware
The middleware uses Buffer.byteLength(ctx.request.rawBody) (where rawBody is the JSON string sent by the client) and ctx.response.length (which Koa sets to the byte-length of the JSON response). Since JSON.stringify(body) produces that same raw string, computing sizes via Buffer.byteLength(JSON.stringify(body)) in the tests yields identical values. No updates to the test expectations are needed.

Likely an incorrect or invalid review comment.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum enabled auto-merge (squash) May 14, 2025 11:37

@koladilip koladilip left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thanks for making this change

@koladilip
koladilip force-pushed the chore.payloadSizeMiddleware branch from cb529d1 to 813c2c1 Compare May 15, 2025 12:36
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented May 15, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.11%. Comparing base (4a18dc9) to head (813c2c1).
Report is 9 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4318      +/-   ##
===========================================
+ Coverage    91.10%   91.11%   +0.01%     
===========================================
  Files          636      636              
  Lines        33378    33378              
  Branches      7888     7894       +6     
===========================================
+ Hits         30410    30414       +4     
+ Misses        2729     2725       -4     
  Partials       239      239              

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

@sonarqubecloud

Copy link
Copy Markdown

@atzoum
atzoum merged commit 6f587c8 into develop May 15, 2025
@atzoum
atzoum deleted the chore.payloadSizeMiddleware branch May 15, 2025 12:44
ItsSudip added a commit that referenced this pull request May 27, 2025
* feat: update destination type with optional account types (#4291)

* feat: update destination type with optional account types

* chore: add authenticationType

* chore: update types with generics

* chore: add optional config to accountDefiition

* chore: update deleteAccount to regulationAccount

* chore: update regulationAccount to deleteAccount

* chore(destination): migrate slack destination tests to new format (#4279)

* chore(destination): migrate slack destination tests to new format

* refactor: tests to use proper types

* chore: fix status in mailchimp, fix cognitive complexity, add unit tests (#4314)

* chore: fix status in mailchimp, fix cognitive complexity, add unit tests

* chore: fix PR comments for mailchimp tests

* test: add tests for error cases to improve code coverage

---------

Co-authored-by: Dilip Kola <[email protected]>

* chore(braze): added docs for braze destination (#4297)

* chore(braze): added docs for braze destination

* chore: update braze docs

* chore: add multiplexing section

---------

Co-authored-by: Utsab Chowdhury <[email protected]>

* chore: add string check for phone in gaoc (#4311)

* chore: add string check for phone in gaoc

* chore: add unit test

* chore: update condition

Co-authored-by: Sudip Paul <[email protected]>

---------

Co-authored-by: Sudip Paul <[email protected]>

* chore: correct dotenv import (#4320)

* chore: payload size middleware performance improvement (#4318)

* fix: add uuid as fallback to missing anonymousId in webhook events (#4276)

* chore: bump codecov/codecov-action from 5.4.2 to 5.4.3 (#4335)

Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 5.4.2 to 5.4.3.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](codecov/codecov-action@v5.4.2...v5.4.3)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-version: 5.4.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: bump slackapi/slack-github-action from 1.27.0 to 2.1.0 (#4312)

Bumps [slackapi/slack-github-action](https://github.com/slackapi/slack-github-action) from 1.27.0 to 2.1.0.
- [Release notes](https://github.com/slackapi/slack-github-action/releases)
- [Commits](slackapi/slack-github-action@v1.27.0...v2.1.0)

---
updated-dependencies:
- dependency-name: slackapi/slack-github-action
  dependency-version: 2.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: mp add content type header to all apis (#4344)

* fix: mp add content-type header and follow strict for engage and group apis

* chore: mp add content type header to all apis

* feat: bluecore email subscription event (#4304)

* fix: blucore optin event mapping

* fix: review comments

* chore: add subscription event

* chore: add subscription event

* fix: reviews comments

* fix: review comments

* fix: review comments

* fix: review comments

* chore: test description

* chore(release): 1.101.0

* chore: pass copy of metadata to avoid actual metadata modifications (#4351)

* Revert "feat: update destination type with optional account types (#4291)" (#4348)

This reverts commit f368f00.

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: Sudip Paul <[email protected]>
Co-authored-by: Yashasvi Bajpai <[email protected]>
Co-authored-by: Dilip Kola <[email protected]>
Co-authored-by: Dilip Kola <[email protected]>
Co-authored-by: Vinay Teki <[email protected]>
Co-authored-by: Utsab Chowdhury <[email protected]>
Co-authored-by: Aris Tzoumas <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Mahesh Kutty <[email protected]>
Co-authored-by: GitHub Actions <[email protected]>
Co-authored-by: Jayachand Mopidevi <[email protected]>
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.

4 participants