Skip to content

chore: add concurrent requests and memory fencing middlewares - #4358

Merged
atzoum merged 2 commits into
developfrom
chore.middlewares
May 29, 2025
Merged

atzoum merged 2 commits into
developfrom
chore.middlewares

Conversation

@atzoum

@atzoum atzoum commented May 27, 2025 •

Copy link
Copy Markdown
Contributor

This pull request introduces two new middlewares, memoryFenceMiddleware and concurrentRequests, to improve server performance and stability by monitoring memory usage and tracking concurrent requests. It also includes tests for both middlewares and updates the Prometheus metrics configuration to support the new functionality.

resolves INT-3677
resolves INT-3675
resolves PIPE-2076

Middleware Enhancements

  • memoryFenceMiddleware:

    • Implements a memory usage threshold to block requests when the server's memory usage exceeds a configurable percentage including response headers (X-Rudder-Should-Retry, X-Rudder-Error-Reason) when fenced. Default threshold is 80%, with a default status code of 503.
    • Tracks the number of blocked requests using a Prometheus counter metric (memory_fenced_requests).
  • concurrentRequests:

    • Tracks the number of concurrent requests being processed and logs this metric at regular intervals (default: every 10 seconds) using a Prometheus gauge metric (http_concurrent_requests). [1] [2]

Middleware Integration

  • Integrated memoryFenceMiddleware and concurrentRequests into the main application (src/index.ts):
    • Memory fencing is enabled conditionally based on the MEMORY_FENCING_ENABLED environment variable.

Testing

  • Added unit tests for memoryFenceMiddleware to verify:
    • Blocking requests when memory usage exceeds the threshold.
    • Allowing requests when memory usage is below the threshold.
    • Handling invalid configuration values and respecting custom options.
  • Added unit tests for concurrentRequests to ensure:
    • Accurate tracking of concurrent requests.
    • Proper logging of metrics at specified intervals.
    • Correct decrementing of counters when requests complete or fail.

Prometheus Metrics

  • Updated Prometheus configuration to include:
    • A counter metric for memory-fenced requests (memory_fenced_requests).
    • A gauge metric for concurrent HTTP requests (http_concurrent_requests).

@atzoum
atzoum requested review from a team and sivashanmukh as code owners May 27, 2025 13:44
@atzoum
atzoum requested review from a team, chandumlg and utsabc May 27, 2025 13:44
@coderabbitai

coderabbitai Bot commented May 27, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Introduced middleware to monitor and limit requests when server memory usage is high, returning a clear error message and status code if limits are exceeded.
    • Added real-time tracking of the number of concurrent requests being processed by the server.
  • Tests

    • Added comprehensive tests to ensure correct behavior of memory usage and concurrent request tracking features.
  • Chores

    • Enhanced metrics reporting with new Prometheus metrics for memory fencing, concurrent requests, and heap size limit.

Summary by CodeRabbit

  • New Features
    • Introduced middleware to monitor and limit requests when server memory usage is high, returning a clear error message and status code if thresholds are exceeded.
    • Added middleware to track and report the number of concurrent HTTP requests being processed.
    • New Prometheus metrics for memory-fenced requests and concurrent requests are now available for improved monitoring.
  • Tests
    • Added comprehensive test suites for both memory fencing and concurrent request tracking middlewares.

Walkthrough

This change introduces two new Koa middleware functions: one for tracking concurrent HTTP requests and another for memory fencing, which blocks requests when memory usage exceeds a threshold. Corresponding Prometheus metrics are defined, and comprehensive unit tests are added to ensure correct middleware behavior under various scenarios.

Changes

File(s) Change Summary
src/index.ts Imports and conditionally applies memoryFenceMiddleware based on env var; always applies concurrentRequests. Added clarifying comments.
src/middlewares/concurrentRequests.ts New middleware tracking concurrent HTTP requests and reporting gauge metrics periodically.
src/middlewares/memoryFencing.ts New middleware blocking requests when memory usage exceeds a configurable threshold, setting status and headers.
src/middlewares/tests/concurrentRequests.test.ts Added tests covering concurrency tracking, metric reporting intervals, and error handling in middleware.
src/middlewares/tests/memoryFencing.test.ts Added tests covering memory threshold logic, blocking behavior, error cases, and metric increments.
src/util/prometheus.js Added Prometheus metrics: memory_fenced_requests (counter), http_concurrent_requests (gauge), and memory_heap_size_limit (gauge).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant KoaApp
    participant MemoryFenceMiddleware
    participant ConcurrentRequestsMiddleware
    participant Handler

    Client->>KoaApp: HTTP Request
    KoaApp->>MemoryFenceMiddleware: Pass request
    alt Memory usage below threshold
        MemoryFenceMiddleware->>ConcurrentRequestsMiddleware: Pass request
        ConcurrentRequestsMiddleware->>Handler: Pass request
        Handler-->>ConcurrentRequestsMiddleware: Response
        ConcurrentRequestsMiddleware-->>KoaApp: Response
        KoaApp-->>Client: HTTP Response
    else Memory usage exceeds threshold
        MemoryFenceMiddleware-->>KoaApp: 503/Custom Status, Memory load message
        KoaApp-->>Client: HTTP Error Response
    end
Loading

Suggested reviewers

  • yashasvibajpai
  • sivashanmukh

Suggestions for improvement:

  • Document the new environment variables (MEMORY_FENCING_ENABLED, MEMORY_FENCE_THRESHOLD_PERCENT, MEMORY_FENCE_STATUS_CODE) and middleware options clearly in the project's configuration guide to aid maintainability.
  • Review the 10-second interval for reporting concurrent requests metrics to ensure it balances performance and monitoring granularity; consider making it configurable if needed.
  • Verify that Prometheus metrics are registered only once, especially in clustered or multi-instance deployments, to prevent metric duplication or conflicts.
  • Consider adding integration or load tests to observe middleware behavior under high concurrency and memory pressure in a production-like environment.
✨ 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:

@codecov

codecov Bot commented May 27, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.11%. Comparing base (c684b65) to head (f5b40c1).
Report is 5 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4358      +/-   ##
===========================================
- Coverage    91.12%   91.11%   -0.01%     
===========================================
  Files          636      639       +3     
  Lines        33400    33435      +35     
  Branches      7896     7887       -9     
===========================================
+ Hits         30435    30465      +30     
- Misses        2696     2731      +35     
+ Partials       269      239      -30     

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

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

Actionable comments posted: 3

🧹 Nitpick comments (7)
src/middlewares/concurrentRequests.ts (1)

4-21: Consider potential race condition and configuration improvements.

The implementation is clean and uses proper try-finally for cleanup. However, there are a few considerations:

  1. Race conditions: The concurrent counter operations aren't atomic, which could lead to inaccurate counts under high concurrency.
  2. Hardcoded interval: The 10-second stats interval is hardcoded.
  3. Multiple instances: If this middleware is used multiple times, each instance maintains separate counters.

Consider these improvements:

+interface ConcurrentRequestsOptions {
+  statsInterval?: number;
+}
+
-export function concurrentRequests(): Middleware {
+export function concurrentRequests(options: ConcurrentRequestsOptions = {}): Middleware {
  let concurrent = 0;
  let lastLogged = Date.now();
-  const statsInterval = 10 * 1000; // 10 seconds
+  const statsInterval = options.statsInterval || 10 * 1000; // 10 seconds

  return async (ctx, next) => {
-    concurrent += 1;
+    const currentCount = ++concurrent; // Atomic increment
    if (Date.now() - lastLogged > statsInterval) {
-      stats.gauge('http_concurrent_requests', concurrent);
+      stats.gauge('http_concurrent_requests', currentCount);
      lastLogged = Date.now();
    }
    try {
      await next();
    } finally {
-      concurrent -= 1;
+      --concurrent; // Atomic decrement
    }
  };
}
src/middlewares/__tests__/memoryFencing.test.ts (1)

69-73: Consider adding boundary condition tests.

The error validation tests are good, but consider adding tests for exact boundary values to ensure the validation logic is precise.

it('throws error for invalid thresholdPercent', () => {
  expect(() => memoryFenceMiddleware({ thresholdPercent: 0 })).toThrow();
  expect(() => memoryFenceMiddleware({ thresholdPercent: 101 })).toThrow();
  expect(() => memoryFenceMiddleware({ thresholdPercent: -5 })).toThrow();
+  // Test boundary conditions
+  expect(() => memoryFenceMiddleware({ thresholdPercent: 1 })).not.toThrow();
+  expect(() => memoryFenceMiddleware({ thresholdPercent: 100 })).not.toThrow();
});
src/middlewares/__tests__/concurrentRequests.test.ts (2)

38-39: Hardcoded interval reduces test maintainability.

The 16-second interval is hardcoded in tests. If the middleware's default interval changes, these tests will break.

Consider making the interval configurable in the middleware and use that configuration in tests:

- // Advance time by 16 seconds
- jest.advanceTimersByTime(16 * 1000);
+ // Advance time by the configured interval
+ jest.advanceTimersByTime(MIDDLEWARE_DEFAULT_INTERVAL);

87-87: Verify gauge reporting timing and accuracy.

While this test checks that the gauge was called with value 2, it doesn't verify when exactly the gauge was called or if multiple gauge calls occurred.

Consider adding more specific assertions:

  await Promise.all([p1, p2]);
+ expect(stats.gauge).toHaveBeenCalledTimes(1); // Ensure it's called only once during the test
  expect(stats.gauge).toHaveBeenCalledWith('http_concurrent_requests', 2);
src/middlewares/memoryFencing.ts (3)

17-18: Consider using RSS memory for more accurate pressure detection.

Using heapUsed/heapTotal might not accurately reflect memory pressure since Node.js can request more heap from the OS. Consider using RSS (Resident Set Size) against available system memory.

- const { heapUsed, heapTotal } = process.memoryUsage();
- const usagePercent = (heapUsed / heapTotal) * 100;
+ const { rss } = process.memoryUsage();
+ const totalMemory = require('os').totalmem();
+ const usagePercent = (rss / totalMemory) * 100;

This provides a more accurate representation of actual memory pressure on the system.


20-25: Add logging for blocked requests to aid debugging.

When requests are blocked due to high memory usage, there's no logging to help with debugging or monitoring. Consider adding a log statement.

  if (usagePercent > thresholdPercent) {
    stats.counter('memory_fenced_requests', 1);
+   console.warn(`Request blocked due to high memory usage: ${usagePercent.toFixed(2)}% > ${thresholdPercent}%`);
    ctx.status = statusCode;
    ctx.body = 'Server is under high memory load. Please try again later.';
    return;
  }

23-23: Consider making the error message configurable.

The error message is hardcoded, which may not be suitable for all use cases or internationalization needs.

Add an optional message parameter to the interface:

interface MemoryFenceOptions {
  thresholdPercent?: number;
  statusCode?: number;
+ message?: string;
}

Then use it in the middleware:

export function memoryFenceMiddleware(options?: MemoryFenceOptions): Middleware {
- const { thresholdPercent = 80, statusCode = 503 } = options || {};
+ const { 
+   thresholdPercent = 80, 
+   statusCode = 503, 
+   message = 'Server is under high memory load. Please try again later.' 
+ } = options || {};

  // ... later in the middleware
- ctx.body = 'Server is under high memory load. Please try again later.';
+ ctx.body = message;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 54fdb8c and 5f42831f74a19663c393aee835d6e4f2f9d42709.

📒 Files selected for processing (6)
  • src/index.ts (1 hunks)
  • src/middlewares/__tests__/concurrentRequests.test.ts (1 hunks)
  • src/middlewares/__tests__/memoryFencing.test.ts (1 hunks)
  • src/middlewares/concurrentRequests.ts (1 hunks)
  • src/middlewares/memoryFencing.ts (1 hunks)
  • src/util/prometheus.js (1 hunks)
🧰 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/util/prometheus.js
🧬 Code Graph Analysis (1)
src/middlewares/__tests__/memoryFencing.test.ts (1)
src/middlewares/memoryFencing.ts (1)
  • memoryFenceMiddleware (9-28)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • 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 (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
src/index.ts (2)

14-15: LGTM: Clean middleware imports added.

The imports are properly structured and follow the existing pattern in the file.


23-24: LGTM: Good addition of clarifying comments and middleware integration.

The comments help clarify the purpose of existing middleware, and the concurrentRequests middleware is properly positioned in the middleware stack.

src/util/prometheus.js (1)

1044-1055: LGTM: Well-defined Prometheus metrics.

The new metrics are properly structured and follow the existing conventions:

  • Appropriate metric types (counter for fenced requests, gauge for concurrent requests)
  • Clear, descriptive help text
  • Consistent naming pattern

These metrics will provide valuable observability for the new middleware functionality.

src/middlewares/__tests__/memoryFencing.test.ts (4)

8-14: LGTM: Good test setup with proper cleanup.

The test setup properly mocks dependencies and restores original state after each test, preventing test interference.


20-35: LGTM: Thorough test coverage for normal operation.

This test properly verifies that the middleware doesn't interfere when memory usage is below the threshold.


37-52: LGTM: Good test for blocking behavior.

Properly tests the core functionality of blocking requests when memory usage exceeds the threshold and verifies the metrics counter is incremented.


1-89:

Details

❌ Incorrect review comment

Consider adding test for concurrentRequests middleware.

The memoryFencing tests are comprehensive, but there's no corresponding test file for the concurrentRequests middleware. Consider adding tests to verify concurrent request counting accuracy and metric reporting.

Would you like me to help create a comprehensive test suite for the concurrentRequests middleware?


🏁 Script executed:

#!/bin/bash
# Check if tests exist for concurrentRequests middleware
fd "concurrentRequests.test" --type f

Length of output: 90


No action needed: tests for concurrentRequests already exist

A test file for the concurrentRequests middleware is present at:

  • src/middlewares/tests/concurrentRequests.test.ts

Please review and enhance that suite if you spot any coverage gaps.

Likely an incorrect or invalid review comment.

Comment thread src/index.ts Resolved
Comment thread src/middlewares/memoryFencing.ts Resolved
@atzoum
atzoum force-pushed the chore.middlewares branch from 5f42831 to 7522bff Compare May 27, 2025 15:09
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

koladilip
koladilip previously approved these changes May 28, 2025

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

Actionable comments posted: 1

♻️ Duplicate comments (2)
src/middlewares/memoryFencing.ts (1)

34-36: Validation logic correctly addresses the previous security concern.

The validation now properly rejects thresholdPercent of exactly 100%, which prevents the dangerous condition mentioned in the previous review. The use of >= 100 ensures requests are blocked before reaching full heap usage.

src/middlewares/__tests__/concurrentRequests.test.ts (1)

21-55: Test still doesn't verify the claimed behavior despite past feedback.

This test has the same issue identified in the previous review - it doesn't actually verify that the concurrent counter is incremented and decremented. The test name suggests it should verify concurrent counter behavior, but it only checks that next() is called.

Consider refactoring to directly test the counter behavior by checking the stats.gauge calls or exposing the counter state for verification.

  it('increments and decrements concurrent counter', async () => {
    const ctx = mockCtx();
-   let concurrentCount = 0;
-   const next = jest.fn(() => {
-     // Capture the concurrent count during execution
-     // Since we can't directly access the internal counter, we'll verify through behavior
-     return Promise.resolve();
-   });
+   const next = jest.fn();

-   // Test that the middleware properly handles the request lifecycle
+   // Advance time to ensure stats.gauge is called
+   jest.advanceTimersByTime(16 * 1000);
    await middleware(ctx, next);
    expect(next).toHaveBeenCalled();
+   expect(stats.gauge).toHaveBeenCalledWith('http_concurrent_requests', 1);
-
-   // Test with a delayed next function to verify counter behavior
-   const ctx2 = mockCtx();
-   let resolveNext: () => void;
-   const delayedNext = jest.fn(
-     () =>
-       new Promise<void>((resolve) => {
-         resolveNext = resolve;
-       }),
-   );
-
-   // Start the middleware but don't complete it yet
-   const promise = middleware(ctx2, delayedNext);
-
-   // Advance time to trigger stats logging
-   jest.advanceTimersByTime(16 * 1000);
-
-   // Complete the request
-   resolveNext!();
-   await promise;
-
-   expect(delayedNext).toHaveBeenCalled();
  });
🧹 Nitpick comments (3)
src/middlewares/memoryFencing.ts (2)

43-44: Consider performance implications of per-request memory checks.

While the memory calculation is mathematically correct, checking process.memoryUsage() on every request could introduce latency in high-traffic scenarios. Consider implementing a caching mechanism or checking memory usage at intervals rather than per-request.

For high-throughput applications, you might want to cache the memory usage calculation:

+ let lastMemoryCheck = 0;
+ let cachedUsagePercent = 0;
+ const MEMORY_CHECK_INTERVAL = 1000; // Check every 1 second

  return async (ctx, next) => {
+   const now = Date.now();
+   if (now - lastMemoryCheck > MEMORY_CHECK_INTERVAL) {
      const { heapUsed, heapTotal } = process.memoryUsage();
-     const usagePercent = (heapUsed / heapTotal) * 100;
+     cachedUsagePercent = (heapUsed / heapTotal) * 100;
+     lastMemoryCheck = now;
+   }
+   const usagePercent = cachedUsagePercent;

46-53: Solid middleware logic with proper early return.

The implementation correctly handles the fencing scenario by incrementing metrics, setting the appropriate status code, and returning early to prevent further processing. The fallback to next() when below threshold is appropriate.

Consider adding debug logging for operational visibility:

  if (usagePercent > thresholdPercent) {
    stats.counter('memory_fenced_requests', 1);
+   console.warn(`Memory fence activated: ${usagePercent.toFixed(2)}% usage exceeds ${thresholdPercent}% threshold`);
    ctx.status = statusCode;
    ctx.body = 'Server is under high memory load. Please try again later.';
    return;
  }
src/middlewares/__tests__/concurrentRequests.test.ts (1)

17-19: Consider extracting mock creation for better reusability.

The mock context function could be enhanced to accept optional parameters for better test flexibility.

- function mockCtx() {
-   return { status: undefined, body: undefined } as any;
- }
+ function mockCtx(overrides = {}) {
+   return { status: undefined, body: undefined, ...overrides } as any;
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7522bfff100e46e789a749b543e5d2cd7954918b and 2b02cb4f6383f13289b1290ac038564d4105a2c4.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json, !**/*.json
📒 Files selected for processing (3)
  • src/middlewares/__tests__/concurrentRequests.test.ts (1 hunks)
  • src/middlewares/__tests__/memoryFencing.test.ts (1 hunks)
  • src/middlewares/memoryFencing.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/middlewares/tests/memoryFencing.test.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/middlewares/__tests__/concurrentRequests.test.ts (1)
src/middlewares/concurrentRequests.ts (1)
  • concurrentRequests (13-30)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
src/middlewares/memoryFencing.ts (3)

1-2: LGTM! Clean imports with appropriate dependencies.

The imports are well-structured, bringing in the necessary Koa middleware type and the stats utility for metrics tracking.


12-15: Well-defined interface with clear documentation.

The interface provides good type safety with optional properties and clear default intentions. The property names are descriptive and the structure is appropriate for configuration options.


38-40: Robust HTTP status code validation.

The validation correctly ensures status codes fall within the valid HTTP range (100-599). The error message is clear and helpful for debugging configuration issues.

src/middlewares/__tests__/concurrentRequests.test.ts (2)

57-71: Well-designed test for stats logging interval.

This test correctly verifies that stats.gauge is only called after the specified interval has passed. The logic and assertions are sound.


81-115: Excellent test for concurrent request tracking.

This test effectively demonstrates that the middleware correctly tracks multiple concurrent requests and reports the accurate count. The use of promises to control request lifecycle timing is well-implemented.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum requested a review from koladilip May 28, 2025 09:30
koladilip
koladilip previously approved these changes May 28, 2025
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/middlewares/memoryFencing.ts (1)

33-35: Past validation issue has been addressed.

The previous concern about allowing 100% threshold has been correctly fixed. The validation now properly excludes 100% by using >= 100, preventing dangerous memory conditions.

🧹 Nitpick comments (2)
src/middlewares/memoryFencing.ts (2)

21-24: Fix documentation inconsistency.

There's a mismatch between the JSDoc documentation and the error message regarding the valid range for thresholdPercent.

- * @param options.thresholdPercent - The memory usage percentage (1-99) at which to start fencing requests. Defaults to 80.
+ * @param options.thresholdPercent - The memory usage percentage (1-99) at which to start fencing requests. Defaults to 80.
- * @throws Will throw an error if `thresholdPercent` is not between 1 and 99.
+ * @throws Will throw an error if `thresholdPercent` is not between 1 and 99.
- throw new Error('thresholdPercent must be between 1 and 100');
+ throw new Error('thresholdPercent must be between 1 and 99');

Also applies to: 34-34


31-35: Consider adding runtime type validation.

While TypeScript provides compile-time type safety, adding runtime validation for the thresholdPercent parameter would prevent unexpected behavior if non-number values are passed at runtime.

  const { thresholdPercent = 80, statusCode = 503 } = options || {};

+ if (typeof thresholdPercent !== 'number') {
+   throw new Error('thresholdPercent must be a number');
+ }
  if (thresholdPercent <= 0 || thresholdPercent >= 100) {
    throw new Error('thresholdPercent must be between 1 and 99');
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4eaaa640797e6e8e3c0353ac2c83ecdf8f88e8f6 and 31f1d6897284505a3cafa57f284ac3da8229d34a.

📒 Files selected for processing (6)
  • src/index.ts (1 hunks)
  • src/middlewares/__tests__/concurrentRequests.test.ts (1 hunks)
  • src/middlewares/__tests__/memoryFencing.test.ts (1 hunks)
  • src/middlewares/concurrentRequests.ts (1 hunks)
  • src/middlewares/memoryFencing.ts (1 hunks)
  • src/util/prometheus.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/middlewares/tests/concurrentRequests.test.ts
  • src/middlewares/tests/memoryFencing.test.ts
  • src/index.ts
  • src/middlewares/concurrentRequests.ts
  • src/util/prometheus.js
⏰ 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 ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
src/middlewares/memoryFencing.ts (1)

37-51: Implementation looks solid.

The middleware logic is well-implemented:

  • Correctly calculates heap usage percentage
  • Properly increments metrics for monitoring
  • Sets appropriate headers for client guidance
  • Returns early without calling next() when fencing is triggered
  • Continues normal processing when memory usage is acceptable

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum force-pushed the chore.middlewares branch from 31f1d68 to e5db246 Compare May 28, 2025 14:48
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum enabled auto-merge May 28, 2025 15:20
@atzoum
atzoum disabled auto-merge May 28, 2025 15:20
@atzoum
atzoum enabled auto-merge (squash) May 28, 2025 15:20
koladilip
koladilip previously approved these changes May 29, 2025
@atzoum
atzoum requested a review from vinayteki95 May 29, 2025 08:02
Comment thread src/index.ts Resolved
Comment thread src/middlewares/concurrentRequests.ts Resolved
Comment thread src/middlewares/memoryFencing.ts Resolved

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

Actionable comments posted: 2

🧹 Nitpick comments (5)
src/middlewares/__tests__/memoryFencing.test.ts (5)

19-22: Add error handling for cleanup operations.

Consider wrapping the cleanup operations in try-catch blocks to prevent test failures if restoration fails.

  afterEach(() => {
-   process.memoryUsage = originalMemoryUsage;
-   jest.clearAllMocks();
+   try {
+     process.memoryUsage = originalMemoryUsage;
+     jest.clearAllMocks();
+   } catch (error) {
+     console.warn('Cleanup failed:', error);
+   }
  });

24-33: Consider expanding the mock context interface.

The mock context covers the essential properties, but consider adding more Koa context properties for future extensibility.

  function mockCtx() {
    return {
      status: undefined,
      body: undefined,
      headers: {},
+     state: {},
+     request: {},
+     response: {},
      set(header: string, value: string) {
        this.headers[header] = value;
      },
    } as any;
  }

54-71: Enhance assertions for blocked request scenario.

The test correctly verifies the blocking behavior, but could benefit from more specific assertions about the response body content.

    expect(ctx.status).toBe(503);
-   expect(ctx.body).toMatch(/high memory load/i);
+   expect(ctx.body).toBe('Server experiencing high memory load');
    expect(stats.counter).toHaveBeenCalledWith('memory_fenced_requests', 1);

89-93: Add test for edge case threshold values.

Consider testing additional edge cases like threshold values very close to 0 and 100, and non-integer values.

  it('throws error for invalid thresholdPercent', () => {
    expect(() => memoryFenceMiddleware({ thresholdPercent: 0 })).toThrow();
    expect(() => memoryFenceMiddleware({ thresholdPercent: 100 })).toThrow();
    expect(() => memoryFenceMiddleware({ thresholdPercent: -5 })).toThrow();
+   expect(() => memoryFenceMiddleware({ thresholdPercent: 0.5 })).toThrow();
+   expect(() => memoryFenceMiddleware({ thresholdPercent: 99.9 })).toThrow();
+   expect(() => memoryFenceMiddleware({ thresholdPercent: NaN })).toThrow();
  });

95-109: Verify default threshold behavior.

The test assumes the default threshold triggers blocking for heapUsed: 900, but it would be more explicit to document what the expected default threshold is.

Add a comment clarifying the default threshold:

  it('uses default options if none provided', async () => {
+   // Default threshold is typically 80%
    process.memoryUsage = jest.fn(() => ({
      heapUsed: 900,
    })) as any;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e5db246 and f5b40c1.

📒 Files selected for processing (3)
  • src/middlewares/__tests__/memoryFencing.test.ts (1 hunks)
  • src/middlewares/memoryFencing.ts (1 hunks)
  • src/util/prometheus.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/middlewares/memoryFencing.ts
  • src/util/prometheus.js
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • 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: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
src/middlewares/__tests__/memoryFencing.test.ts (1)

5-14: Well-structured mocking setup.

The mocking approach correctly isolates the middleware dependencies and provides predictable test behavior. The default heap_size_limit of 1000 provides a clean baseline for calculations.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

Copy link
Copy Markdown

@atzoum
atzoum requested review from koladilip and vinayteki95 May 29, 2025 09:51
@atzoum
atzoum merged commit 9a0fca4 into develop May 29, 2025
@atzoum
atzoum deleted the chore.middlewares branch May 29, 2025 11:48
koladilip added a commit that referenced this pull request Jun 30, 2025
* fix: handle empty oauth secret for multiple destination (#4295)

* fix: handle empty oauth secret for multiple destination

* fix: test

* fix: add validation for other field

* chore: add missing test

* chore: add more test

* chore: change test

* chore: misc

* feat: implement hasDynamicConfig flag support (#4321)

* feat: implement hasDynamicConfig flag support in routerTransform flow

This implements support for the hasDynamicConfig flag in the routerTransform flow to fix
the issue where events with dynamic configuration were being mixed up during transformation.
The implementation includes:

1. Added a new hasDynamicConfig flag to the Destination type in controlPlaneConfig.ts to indicate
 whether a destination's configuration contains dynamic config patterns
2. Modified the dynamicConfigParser.ts to respect the hasDynamicConfig flag:
   - Skip processing when hasDynamicConfig is explicitly false
   - Process events when hasDynamicConfig is true or undefined (for backward compatibility)
3. Enhanced groupRouterTransformEvents function in src/v0/util/index.js to:
   - Group events by destination config when hasDynamicConfig is true or undefined
   - Use fast-json-stable-stringify to ensure consistent grouping of configs with different key orders
   - Maintain backward compatibility with older server versions where the flag might not be present
4. Added comprehensive test cases for:
   - Testing behavior with hasDynamicConfig=false
   - Testing behavior with hasDynamicConfig=true
   - Testing backward compatibility with hasDynamicConfig=undefined
   - Testing mixed hasDynamicConfig flags in a batch
   - Testing configs with different key orders

This implementation resolves INT-3633 by ensuring that events with dynamic configuration are properly
 grouped and processed in the routerTransform flow, preventing event mix-up issues.

Dependencies:
- Added fast-json-stable-stringify package to ensure consistent JSON string representation regardless of key order

* fix: add hasDynamicConfig flag support in routerTransform flow

* test: add hasDynamicConfig flag to test files

fix tests

* refactor: optimize dynamicConfigParser to avoid deep cloning entire event

* fix: restore unset functionality in dynamic config parser

- Add unset-value import to properly remove extracted fields from events
- Restore unset() call after extracting dynamic config values to prevent downstream issues
- Change from shallow to deep cloning to avoid modifying original events during unset operations
- Add comprehensive test to verify unset functionality works correctly
- Add shouldGroupByDestinationConfig method to JavaScript dynamic config module
- Update groupRouterTransformEvents to use shouldGroupByDestinationConfig function
- Add environment variable tests for USE_HAS_DYNAMIC_CONFIG_FLAG in router grouping logic

This ensures that fields used in dynamic config templates (e.g., {{ message.traits.appId || 'default' }})
are properly removed from events after extraction, preventing potential conflicts in destination processing.

* refactor: optimize dynamic config parser and consolidate utilities

- Move utility functions from dynamicConfig.js to utils.js for better organization
- Optimize DynamicConfigParser with pre-compiled regex patterns and efficient loops
- Replace deep cloning with selective cloning for better performance
- Remove standalone dynamicConfig.js and dynamicConfig.test.js files
- Update imports and references across affected modules

* fix: ensure consistent ordering in batch processing for google adwords offline conversions (#4359)

- Add sorting by jobId to removeDuplicateMetadata function
- Sort final batch results by minimum jobId for consistent ordering
- Re-enable router output assertion for google_adwords_offline_conversions tests
- Update test data ordering to match new consistent batch processing behavior
- Fix unit test expectations to match new sorted metadata order

* chore: add concurrent requests and memory fencing middlewares (#4358)

* chore: migrate tiktok_ads to new test (#4342)

* chore: migrate tiktok_ads to new test

* chore: review comments

* chore: review comments

* chore: review comments

* chore: review comments

* chore: rebase

* chore: introduce deep freeze to compaction middlewares (#4365)

* feat: implement rudder-test destination with migrated tests (#4352)

- Add rudder-test destination for platform testing and development
- Implement TypeScript destination with router-only transformation
- Support Record v2 events with echo response pattern
- Add context-based test behavior control via testBehavior field
- Migrate tests to new format using migration script
- Optimize tests with generateMetadata utility and common destination
- Enable Zod validation and enhanced Allure reporting
- Add npm script 'rudder-tests' for convenient test execution
- Update README.md with comprehensive destination documentation

The rudder-test destination provides a controlled testing environment
without external dependencies, ideal for platform feature testing,
development workflows, and CI/CD reliability.

refactor: reduce code duplication in rudder_test destination

- Extract common validation and request building logic to utils.ts
- Add processor transformation function alongside existing router function
- Create comprehensive component tests for both processor and router
- Implement shared utilities for message validation, request config building, and test behavior handling
- Maintain different error handling patterns for processor (throws) vs router (returns error objects)
- Add 6 test cases covering success scenarios, error responses, and validation failures

refactor: improve type safety in rudder_test utils

- Replace 'any' types with specific Metadata and RudderTestDestination types
- Import proper types from '../../../types' for better type safety
- Enhance IntelliSense support and compile-time error detection
- Address coderabbitai bot feedback on PR #4352

feat: enhance rudder_test destination with comprehensive dynamic config testing

- Modified rudder_test destination to actually use resolved dynamic config values
- Added endpoint and apiKey resolution from destination config in utils.ts
- Updated transform.ts to pass destination config to utility functions
- Enhanced type definitions to support RudderTestConfig interface

- Added multi-event test cases for both processor and router
- Tests validate multiple events with different dynamic config values resolve correctly
- Added mixed destination ID scenarios (different hasDynamicConfig flags)
- Added compaction tests with multiple events and dynamic config
- All 20 tests now pass and actually validate dynamic config resolution

These tests will surface thread safety issues and shared state problems
in dynamic config processing by testing scenarios where multiple events
have different template variable values that must resolve independently.

docs: update rudder_test destination documentation with dynamic config features

- Added dynamic config resolution capabilities to feature list
- Updated implementation details to reflect both processor and router support
- Added comprehensive test coverage information (20 test cases)
- Included dynamic config examples with template syntax
- Added multi-event testing and thread safety testing use cases
- Updated key files list to include utils.ts and enhanced type definitions
- Corrected architecture description from router-only to dual implementation

* chore: sfmc ai generated docs (#4328)

* chore: sfmc ai generated docs

* chore: sfmc api section in docs

* chore: separate out transformer logic from main doc

* chore: vdm-v2 related faulty docs fix

* Revert "Revert "Merge branch 'develop' into main""

This reverts commit af6e580.

* fix: klaviyo error logging

* chore: optimize usage of deepFreeze in compaction middlewares (#4374)

* chore: use batch processing in transformations (#4363)

* feat: use account information on zoho (#4361)

* chore: new way of creating release

* fix: deep freeze in compaction middleware

- Add test behaviors in rudder_test transform to mutate and replace destination config
- Add router and processor component tests for both property mutation and config
  reference replacement in compacted payload flow
- Assert correct error handling and status codes when mutation is attempted on frozen config
- Ensures immutability of config is enforced and covered in both flows
- Remove unneccessary clonedeep in router transform flow by fixing code

* chore: add safe batch processing to avoid blocking in highly batched destinations

* chore: add batching in mp and source transformations

* fix(marketo): remove auth key from logs

* feat: testing tool (#4391)

* feat: testing tool

* chore: changes

* chore: code structure

* fix: eslint

* chore: review comments

* chore: review comment

* feat: add server request creation flow

* chore: bluecore add internal doc and migrate test (#4353)

* fix: blucore optin event mapping

* fix: review comments

* chore: add subscription event

* chore: add subscription event

* fix: reviews comments

* chore: blucore add internal doc and migrate test

* chore: misc

* chore: misc

* fix: readme

* chore: update docs

* fix(bluecore): address PR #4353 reviewer feedback and API documentation corrections

✅ Complete reviewer feedback resolution:
- Removed all 16 'NEEDS REVIEW' placeholders with concrete information
- Removed AI-generated optimization recommendations section
- Simplified repetitive business logic content by creating detailed businesslogic.md
- Updated documentation structure to follow rs-ai repository standards

🔧 API Documentation Corrections:
- Corrected API type from 'Transactional API' to 'Events API' throughout documentation
- Updated endpoint information to reflect actual implementation: https://api.bluecore.app/api/track/mobile/v1
- Fixed authentication method documentation (namespace token in payload vs Bearer header)
- Updated rate limiting information to reflect Events API (removed incorrect Transactional API limits)
- Updated References section with official Events API documentation link

📚 Documentation Structure Improvements:
- Created comprehensive businesslogic.md with detailed field mappings and transformation flows
- Streamlined main README by removing repetitive sections and adding cross-references
- Consolidated error handling, testing, and performance sections
- Updated RETL documentation for consistency

🔍 Code Analysis Verification:
- Verified endpoint match between code implementation and documentation
- Confirmed authentication method matches actual implementation
- Validated all API references against official Bluecore Events API documentation

Files modified:
- src/cdk/v2/destinations/bluecore/README.md (extensive updates)
- src/cdk/v2/destinations/bluecore/docs/businesslogic.md (created)
- src/cdk/v2/destinations/bluecore/docs/retl.md (updated)

The documentation now accurately reflects the actual Bluecore Events API implementation
and provides reliable information for users integrating with Bluecore through RudderStack.

* chore: docs

* chore: review comments

* fix: review comments

* fix: review comments

* fix: review comments

* chore: improve release check reliability

* fix: ensure the testing tool is cross-platform compatible (#4401)

* fix: make testing tool compatible with cross plateform

* fix: review comments

* fix: review comments

* chore: update klaviyo version to 2024-10-15, remove config restricted changes (#4387)

* chore: criteo audience api version upgrade (#4382)

* chore: criteo audience api version upgrade

* chore: add destination integration doc

* chore: resolving comments

* chore: groupEventsByType function optimization (#4398)

* fix: rt event ordering for hs (#4397)

* fix: router output ordering for tiktok_ads

* fix: test

* fix: test

* fix: test

* fix: rt event ordering for hs

* test: configure batch processing defaults for component tests

* fix: test folder structure for destinations (#4414)

* feat: update workflow to raise pr for dedicated transformer from operator (#4413)

* feat: update workflow to raise pr for dedicated transformer from operator

* Update .github/workflows/prepare-for-prod-dt-deploy.yml

Co-authored-by: Krishna Chaitanya <[email protected]>

* chore: revert rollback changes

---------

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

* chore: remove broken workflow to updating dedicated deployment (#4418)

chore: remove broken updating dedicated deployment workflow

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

* chore: update node version to 20.19.2 (#4416)

* chore(mailchimp): add router test with inputs contains different destnations (#4419)

* chore(mailchimp): add router test with inputs contains different destinations

* chore: misc

* chore(release): 1.103.0

* fix: enhance config object in ga4 v2 instead of mutating it (#4436)

* fix: enhance config object in ga4v2 instead of mutation

* chore: update changelog

---------

Co-authored-by: Utsab Chowdhury <[email protected]>
Co-authored-by: Mahesh Kutty <[email protected]>
Co-authored-by: Dilip Kola <[email protected]>
Co-authored-by: Aris Tzoumas <[email protected]>
Co-authored-by: Vinay Teki <[email protected]>
Co-authored-by: Sudip Paul <[email protected]>
Co-authored-by: Dilip Kola <[email protected]>
Co-authored-by: Yashasvi Bajpai <[email protected]>
Co-authored-by: Manish Kumar <[email protected]>
Co-authored-by: Sudip Paul <[email protected]>
Co-authored-by: Krishna Chaitanya <[email protected]>
Co-authored-by: GitHub Actions <[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