Skip to content

feat: add spread middleware which will help to spread information around the event body - #4186

Merged
ItsSudip merged 6 commits into
developfrom
feat.add_spreader_middleware
Apr 8, 2025
Merged

ItsSudip merged 6 commits into
developfrom
feat.add_spreader_middleware

Conversation

@ItsSudip

@ItsSudip ItsSudip commented Mar 20, 2025 •

Copy link
Copy Markdown
Member

What are the changes introduced in this PR?

We are creating a middleware that will help to spread data all over the event body.

What is the related Linear task?

Resolves INT-3390

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

Any technical or performance related pointers to consider with the change?

N/A

@coderabbitai review


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • Is the PR limited to 10 file changes?

  • Is the PR limited to one linear task?

  • Are relevant unit and component test-cases added in new readability format?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

@coderabbitai

coderabbitai Bot commented Mar 20, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Introduced the ArraySpreader middleware for dynamic data transformation based on configurable rules.
    • Added the SecretSpreader middleware to enhance request handling in the routing logic.
    • Implemented new interfaces for defining data spreading rules and configurations.
  • Bug Fixes

    • Ensured that the middleware handles empty arrays without throwing errors during processing.
  • Tests

    • Added a test suite for the ArraySpreader middleware to validate its functionality across various scenarios.

Walkthrough

The pull request introduces a middleware system to spread data across arrays. An abstract class (BaseSpreader) is created to handle extraction and transformation of values from requests, while a concrete class (ArraySpreader) extends it to apply spread data to each array element. A dedicated instance, SecretSpreader, is configured with specific rules and is incorporated into a route. Additionally, interfaces for configuration and context are defined, and tests are implemented to validate the middleware’s behavior across various scenarios, including handling nested values and empty arrays.

Changes

File(s) Change Summary
src/middlewares/arraySpreader.ts, src/middlewares/baseSpreader.ts Introduces new middleware classes. BaseSpreader provides core functionality for data extraction and transformation, while ArraySpreader implements array-specific spreading logic with helper methods.
src/middlewares/tests/arraySpreader.test.ts Adds tests to verify that ArraySpreader correctly applies spread data to array items, handles nested paths, and manages empty arrays without errors.
src/middlewares/types/spreader.ts Introduces interfaces (SpreadRule, SpreaderConfig, and SpreaderContext) to standardize configuration and context for the spreading middleware.
src/routes/destination.ts Integrates the SecretSpreader.middleware() into the POST route ('/routerTransform'), positioning it within the middleware chain prior to the destination controller.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Router as Koa Router
    participant MS as SecretSpreader (ArraySpreader)
    participant Controller as DestinationController

    Client ->> Router: POST /routerTransform
    Router ->> MS: Invoke SecretSpreader.middleware()
    MS ->> MS: Extract values from headers, body, and query via BaseSpreader
    MS ->> MS: Process spreadData using applySpreadData (calls getNestedValue/setNestedValue)
    MS -->> Router: Return modified request context
    Router ->> Controller: Forward request to destinationTransformAtRouter
    Controller -->> Router: Send response
    Router -->> Client: Return final response
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

@codecov

codecov Bot commented Mar 20, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 96.49123% with 2 lines in your changes missing coverage. Please review.

Project coverage is 91.05%. Comparing base (322ddbc) to head (44ce4b3).
Report is 10 commits behind head on develop.

Files with missing lines Patch % Lines
src/middlewares/baseSpreader.ts 93.33% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4186      +/-   ##
===========================================
- Coverage    91.05%   91.05%   -0.01%     
===========================================
  Files          627      628       +1     
  Lines        33049    32990      -59     
  Branches      7818     7808      -10     
===========================================
- Hits         30092    30038      -54     
- Misses        2710     2735      +25     
+ Partials       247      217      -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.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@ItsSudip
ItsSudip marked this pull request as ready for review March 24, 2025 17:12
@ItsSudip
ItsSudip requested a review from sivashanmukh as a code owner March 24, 2025 17:12
@ItsSudip
ItsSudip requested a review from a team March 24, 2025 17:12

@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 (3)
src/middlewares/arraySpreader.ts (2)

4-27: Optimize the rule lookup in the applySpreadData method.

The same rule lookup operation this.config.rules.find((rule) => rule.target.path === key) is performed twice in lines 10 and 11-12, which is inefficient, especially if there are many rules.

Consider storing the result of the first lookup and reusing it:

 // Apply spread data to each array item
 Object.entries(ctx.spreadData).forEach(([key, value]) => {
-  if (this.config.rules.find((rule) => rule.target.path === key)?.target.arrayPath) {
-    const arrayPath = this.config.rules.find((rule) => rule.target.path === key)?.target
-      .arrayPath;
+  const matchingRule = this.config.rules.find((rule) => rule.target.path === key);
+  if (matchingRule?.target.arrayPath) {
+    const arrayPath = matchingRule.target.arrayPath;
     let array: any[] = [];
     if (arrayPath) {
       array = this.getNestedValue(body, arrayPath);
     }

29-44: Add test coverage for edge cases in setNestedValue.

The setNestedValue method has lines that aren't covered by tests according to static analysis. Consider adding tests for these scenarios to ensure robustness.

Specifically, add tests for:

  1. Cases where parts of the nested path don't exist
  2. Edge cases with falsy values
  3. Different types of nested objects
// Example test to add
it('should create nested objects when parts of the path do not exist', async () => {
  // Arrange
  const config = { name: 'test', rules: [] };
  const arraySpreader = new ArraySpreader(config);
  const obj = {};
  
  // Act - use private method through reflection or test a public method that uses it
  // @ts-ignore - accessing private method for testing
  arraySpreader['setNestedValue'](obj, 'deeply.nested.property', 'value');
  
  // Assert
  expect(obj).toEqual({ deeply: { nested: { property: 'value' } } });
});
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 36-40: src/middlewares/arraySpreader.ts#L36-L40
Added lines #L36 - L40 were not covered by tests

src/middlewares/baseSpreader.ts (1)

31-42: Potential extension to support additional source types.
Currently, only header, body, and query are supported. Consider extending this method to handle other sources like path parameters if needed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d641594 and a5ac1a0.

📒 Files selected for processing (5)
  • src/middlewares/arraySpreader.ts (1 hunks)
  • src/middlewares/baseSpreader.ts (1 hunks)
  • src/middlewares/tests/arraySpreader.test.ts (1 hunks)
  • src/middlewares/types/spreader.ts (1 hunks)
  • src/routes/destination.ts (2 hunks)
🧰 Additional context used
🧬 Code Definitions (4)
src/routes/destination.ts (1)
src/middlewares/arraySpreader.ts (1)
  • SecretSpreader (48-63)
src/middlewares/baseSpreader.ts (1)
src/middlewares/types/spreader.ts (2)
  • SpreaderConfig (15-19)
  • SpreaderContext (21-23)
src/middlewares/arraySpreader.ts (1)
src/middlewares/types/spreader.ts (1)
  • SpreaderContext (21-23)
src/middlewares/tests/arraySpreader.test.ts (1)
src/middlewares/arraySpreader.ts (1)
  • ArraySpreader (4-45)
🪛 GitHub Check: codecov/patch
src/middlewares/arraySpreader.ts

[warning] 36-40: src/middlewares/arraySpreader.ts#L36-L40
Added lines #L36 - L40 were not covered by tests

🔇 Additional comments (14)
src/routes/destination.ts (2)

6-6: Import statement looks good.

The import for the SecretSpreader is correctly added, facilitating the integration of the new middleware functionality.


22-22: Middleware integration looks good.

The SecretSpreader.middleware() is properly integrated into the middleware chain for the /routerTransform route, positioned logically after the route activation and feature flag middleware and before the controller method.

src/middlewares/types/spreader.ts (3)

3-13: Well-defined interface for spread rules.

The SpreadRule interface provides a clear structure for defining how data should be spread from a source to a target, with appropriate type constraints and optional transformation capability.


15-19: Good configuration interface design.

The SpreaderConfig interface provides a clean way to configure the spreader with an array of rules, a name for identification, and an optional description for documentation purposes.


21-23: Appropriate extension of Koa Context.

The SpreaderContext interface correctly extends Koa's Context to include the spreadData property, which will be used to store the data that will be spread across array elements.

src/middlewares/tests/arraySpreader.test.ts (3)

4-42: Test case correctly verifies basic array spreading functionality.

This test effectively validates that the ArraySpreader middleware correctly applies spread data (tenant ID) to each item in an array based on the configuration rules.


44-74: Test case thoroughly validates nested path handling.

The test properly verifies that the ArraySpreader can correctly set nested values within array items, demonstrating the dot notation path functionality works as expected.


76-106: Edge case handling for empty arrays is well-tested.

The test appropriately verifies that the ArraySpreader handles empty arrays gracefully without throwing errors, which is important for robustness in production environments.

src/middlewares/arraySpreader.ts (1)

29-44:

Details

❓ Verification inconclusive

Consider handling falsy values consistently in setNestedValue.

The current implementation only sets values when value is truthy (line 40), which means falsy values like false, 0, or empty strings won't be set. This might be intentional, but ensure it aligns with the expected behavior throughout the application.

Consider modifying the check to allow setting all values including falsy ones (except undefined and null):

 private setNestedValue(obj: any, path: string, value: any): void {
   const parts = path.split('.');
   const last = parts.pop();

   if (last) {
     const target = parts.reduce((acc, part) => {
       if (!acc[part]) {
         acc[part] = {};
       }
       return acc[part];
     }, obj);
-    if (value) {
+    if (value !== undefined && value !== null) {
       target[last] = value;
     }
   }
 }

Run the following script to verify if falsy values are used in the codebase:


🏁 Script executed:

#!/bin/bash
# Check for usage patterns of setNestedValue with falsy values
rg -A 3 "setNestedValue|target\[last\]" --type typescript

Length of output: 94


I've updated the review comment to reflect that while switching to a more inclusive falsy value check is a good idea, the automated verification wasn’t conclusive. Please make sure that allowing falsy values (like 0, false, or empty strings) does not break any intended behavior in the application.

  • The current logic only assigns the value if it's truthy, which may be skipping valid falsy values.
  • The proposed change is to update the condition from:
       if (value) {
    to:
       if (value !== undefined && value !== null) {
  • Since our initial verification script encountered issues (it reported an unrecognized file type), please manually verify that all usages of setNestedValue in the codebase handle falsy values as expected.
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 36-40: src/middlewares/arraySpreader.ts#L36-L40
Added lines #L36 - L40 were not covered by tests

src/middlewares/baseSpreader.ts (5)

1-3: Well-structured import statements.
No issues found with the import declarations and usage of types.


4-6: Clear and concise class definition.
The abstract class design aligns with typical middleware patterns and naming conventions.


7-9: Constructor logic is straightforward.
Storing the config is handled properly; no concerns.


44-46: Robust nested value access.
Using optional chaining with reduce is a concise and clean approach. No issues found.


48-48: Abstract method encourages consistent subclass implementation.
Requiring subclasses to implement their own data-application logic is a good design choice.

Comment thread src/middlewares/arraySpreader.ts Resolved
Comment thread src/middlewares/baseSpreader.ts Resolved
@ItsSudip ItsSudip changed the title feat: add spreade middleware which will help to spread information around the event body feat: add spread middleware which will help to spread information around the event body Mar 27, 2025
@koladilip

Copy link
Copy Markdown
Contributor

make sure to have 100% coverage

Comment thread src/middlewares/baseSpreader.ts Resolved
@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/baseSpreader.ts (1)

17-31: 🛠️ Refactor suggestion

Handle asynchronous transforms properly.

This block processes each rule synchronously and does not await the transform if it returns a Promise. This concern matches a past comment pointing out that asynchronous transformations won't be handled correctly with forEach.

A potential fix is to replace forEach with a for...of loop, ensuring we can await each transform:

- this.config.rules.forEach((rule) => {
-   const value = this.extractValue(spreaderCtx, rule.source);
-   if (value !== undefined) {
-     try {
-       spreaderCtx.spreadData[rule.target.path] = rule.transform
-         ? rule.transform(value)
-         : value;
-     } catch (e) {
-       throw new PlatformError(
-         `Error applying transform function for rule: ${JSON.stringify(rule)}`,
-       );
-     }
-   }
- });
+ for (const rule of this.config.rules) {
+   const value = this.extractValue(spreaderCtx, rule.source);
+   if (value !== undefined) {
+     try {
+       spreaderCtx.spreadData[rule.target.path] = rule.transform
+         ? await rule.transform(value)
+         : value;
+     } catch (e) {
+       throw new PlatformError(
+         `Error applying transform function for rule: ${JSON.stringify(rule)}`,
+       );
+     }
+   }
+ }
🧹 Nitpick comments (3)
src/middlewares/baseSpreader.ts (3)

25-28: Include the original error message for better debugging.

Currently, the code rethrows a generic PlatformError. Adding the original error message can help with faster troubleshooting.

} catch (e) {
-  throw new PlatformError(
-    `Error applying transform function for rule: ${JSON.stringify(rule)}`,
-  );
+  throw new PlatformError(`
+    Error applying transform function for rule: ${JSON.stringify(rule)}.
+    Original error: ${e instanceof Error ? e.message : e}
+  `);
}

40-50: Check for unrecognized source types.

Although returning undefined by default is valid, consider warning or throwing an error if the source type is not recognized to quickly expose bugs or misconfigurations.


53-55: Support array indexing in nested paths if required.

This method currently splits on dots and returns undefined for any array indexing in the path. If you expect array indices, consider an enhanced parser for nested paths.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a5ac1a0 and 28d7567.

⛔ Files ignored due to path filters (1)
  • src/middlewares/tests/arraySpreader.test.ts is excluded by !**/tests/**
📒 Files selected for processing (1)
  • src/middlewares/baseSpreader.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/middlewares/baseSpreader.ts (1)
src/middlewares/types/spreader.ts (2)
  • SpreaderConfig (15-19)
  • SpreaderContext (21-23)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • 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: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: ingestion-service-test
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@ItsSudip

ItsSudip commented Apr 7, 2025

Copy link
Copy Markdown
Member Author

make sure to have 100% coverage

Only baseSpreader is at 95.23% as the default scenario in the extractValue function is not creatable.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

sonarqubecloud Bot commented Apr 7, 2025

Copy link
Copy Markdown

@ItsSudip
ItsSudip merged commit d72fbaa into develop Apr 8, 2025
@ItsSudip
ItsSudip deleted the feat.add_spreader_middleware branch April 8, 2025 03:00
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.

5 participants