Repository navigation
chore: add concurrent requests and memory fencing middlewares - #4358
Conversation
Summary by CodeRabbit
Summary by CodeRabbit
WalkthroughThis 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
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
Suggested reviewers
Suggestions for improvement:
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
Documentation and Community
|
|
Allure Test reports for this run are available at:
|
Codecov ReportAll modified and coverable lines are covered by tests ✅
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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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:
- Race conditions: The concurrent counter operations aren't atomic, which could lead to inaccurate counts under high concurrency.
- Hardcoded interval: The 10-second stats interval is hardcoded.
- 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/heapTotalmight 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
messageparameter 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 fLength 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.
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
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
thresholdPercentof exactly 100%, which prevents the dangerous condition mentioned in the previous review. The use of>= 100ensures 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.gaugecalls 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.jsonis 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.gaugeis 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.
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
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
thresholdPercentparameter 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
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
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
📒 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.
|
Allure Test reports for this run are available at:
|
|
* 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]>



This pull request introduces two new middlewares,
memoryFenceMiddlewareandconcurrentRequests, 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:memory_fenced_requests).concurrentRequests:http_concurrent_requests). [1] [2]Middleware Integration
memoryFenceMiddlewareandconcurrentRequestsinto the main application (src/index.ts):MEMORY_FENCING_ENABLEDenvironment variable.Testing
memoryFenceMiddlewareto verify:concurrentRequeststo ensure:Prometheus Metrics
memory_fenced_requests).http_concurrent_requests).