Skip to content

feat(mp): add validation for property limits in mixpanel destination - #4233

Merged
koladilip merged 1 commit into
developfrom
chore/add-validation-properties-length
Apr 7, 2025
Merged

koladilip merged 1 commit into
developfrom
chore/add-validation-properties-length

Conversation

@koladilip

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

Add validation to ensure mixpanel properties adhere to documented limits:

  • Maximum of 255 properties per object
  • Maximum of 255 elements per array
  • Maximum nesting depth of 3
  • Maximum payload size of 1MB

Add comprehensive tests to verify validation functionality works correctly.

What is the related Linear task?

Resolves INT-3478

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.

@koladilip
koladilip requested a review from a team as a code owner April 4, 2025 05:34
@coderabbitai

coderabbitai Bot commented Apr 4, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Enhanced event tracking by enforcing stricter validations on data payloads, ensuring that submitted event details remain within prescribed limits for size and structure.
  • Tests
    • Introduced comprehensive tests to verify robust handling of various event data scenarios, ensuring consistent and reliable event processing.

Walkthrough

This pull request introduces new constants in the configuration module to set limits on Mixpanel event properties. A new function, validateMixpanelPayloadLimits, is implemented in the utility module to validate property objects against these limits, which include checks for arrays, nested objects, and overall payload sizes. Modifications in the transformation module ensure that these validations are applied across various event types before constructing payloads. Additionally, a comprehensive test suite is added to verify the correct behavior of the validation logic under multiple scenarios.

Changes

File(s) Change Summary
src/v0/destinations/mp/config.js Added and exported constants: MAX_PROPERTY_KEYS_COUNT (255), MAX_ARRAY_ELEMENTS_COUNT (255), MAX_NESTING_DEPTH (3), and MAX_PAYLOAD_SIZE_BYTES (1MB).
src/v0/destinations/mp/util.js Introduced the validateMixpanelPayloadLimits function with recursive validation and error handling for limits; updated createIdentifyResponse to invoke this function; exported the new validation function.
src/v0/destinations/mp/transform.js Integrated calls to validateMixpanelPayloadLimits within event processing functions to ensure property limits are enforced before payload construction.
src/v0/destinations/mp/util.test.js Added a comprehensive test suite for validateMixpanelPayloadLimits that covers valid inputs, excessive property counts, array elements, deep nesting, and handling of non-object inputs.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Event Source
    participant Transform as Transform Module
    participant Validator as Util Module (Validation)
    
    Client->>Transform: Submit event with properties
    Transform->>Validator: validateMixpanelPayloadLimits(properties)
    Validator-->>Transform: Return validation result (pass or error)
    Transform->>Client: Process event (or return error)
Loading
sequenceDiagram
    participant Client as Identify Source
    participant Util as Util Module
    participant Service as Tracking Service

    Client->>Util: createIdentifyResponse(message)
    Util->>Util: validateMixpanelPayloadLimits(traits)
    Util-->>Client: Return validated identify payload
    Client->>Service: Send identify event payload
Loading

Possibly related PRs

Suggested reviewers

  • yashasvibajpai
  • sandeepdsvs
  • utsabc
  • vinayteki95
  • maheshkutty
  • ItsSudip
✨ 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.

@koladilip
koladilip force-pushed the chore/add-validation-properties-length branch from 88778f1 to 6d3b0a3 Compare April 4, 2025 05:35
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Apr 4, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 97.05882% with 1 line in your changes missing coverage. Please review.

Project coverage is 91.04%. Comparing base (322ddbc) to head (8a08739).
Report is 9 commits behind head on develop.

Files with missing lines Patch % Lines
src/v0/destinations/mp/util.js 96.29% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4233      +/-   ##
===========================================
- Coverage    91.05%   91.04%   -0.01%     
===========================================
  Files          627      626       -1     
  Lines        33049    32958      -91     
  Branches      7818     7802      -16     
===========================================
- Hits         30092    30007      -85     
- Misses        2710     2734      +24     
+ 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.

vinayteki95
vinayteki95 previously approved these changes Apr 4, 2025
@vinayteki95

Copy link
Copy Markdown
Contributor

Code smells and test coverage improvement required - We can create a tech-debt ticket to deal with it later. Approving for now.

ItsSudip
ItsSudip previously approved these changes Apr 4, 2025
Comment thread src/v0/destinations/mp/transform.js Resolved
@koladilip
koladilip dismissed stale reviews from ItsSudip and vinayteki95 via f8582c8 April 4, 2025 07:40
@koladilip
koladilip force-pushed the chore/add-validation-properties-length branch 2 times, most recently from f8582c8 to 30d28c8 Compare April 4, 2025 07:41
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

vinayteki95
vinayteki95 previously approved these changes Apr 4, 2025
@koladilip
koladilip force-pushed the chore/add-validation-properties-length branch from 30d28c8 to bd60839 Compare April 4, 2025 10:22
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

Add validation to ensure mixpanel properties adhere to documented limits:
- Maximum of 255 properties per object
- Maximum of 255 elements per array
- Maximum nesting depth of 3
- Maximum payload size of 1MB

Add comprehensive tests to verify validation functionality works correctly.
@koladilip
koladilip force-pushed the chore/add-validation-properties-length branch from bd60839 to 8a08739 Compare April 4, 2025 11:39

@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

🧹 Nitpick comments (2)
src/v0/destinations/mp/util.js (1)

90-113: Consider adding error handling for JSON.stringify

The function is well-implemented but vulnerable to uncaught exceptions if the payload contains circular references when using JSON.stringify().

const validateMixpanelPayloadLimits = (payload) => {
  if (!isDefinedAndNotNull(payload)) {
    return;
  }
-  const payloadSize = Buffer.byteLength(JSON.stringify(payload));
+  let payloadString;
+  try {
+    payloadString = JSON.stringify(payload);
+  } catch (error) {
+    throw new InstrumentationError(`Failed to stringify Mixpanel payload: ${error.message}`);
+  }
+  const payloadSize = Buffer.byteLength(payloadString);
  if (payloadSize > MAX_PAYLOAD_SIZE_BYTES) {
    throw new InstrumentationError(
      `Mixpanel payload exceeds the maximum size limit of 1MB (found ${Math.round(payloadSize / 1024)} KB)`,
    );
  }

  // Start the recursive validation
  validateObjectRecursively(payload, '', 0);
};
src/v0/destinations/mp/util.test.js (1)

794-934: Consider adding test for payloads exceeding size limit.

While the test suite is comprehensive for structure limits, there's no test for the payload size validation which checks against MAX_PAYLOAD_SIZE_BYTES.

You should add a test case that creates a large payload exceeding 1MB to ensure the size validation works correctly:

it('should throw error when payload size exceeds the maximum', () => {
  // Create a large string that will exceed 1MB when stringified
  const largeValue = 'a'.repeat(1024 * 1024);
  const properties = { largeProperty: largeValue };

  expect(() => validateMixpanelPayloadLimits(properties)).toThrow(InstrumentationError);
  expect(() => validateMixpanelPayloadLimits(properties)).toThrow(
    'Mixpanel payload exceeds the maximum size limit of 1MB'
  );
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd608396a4c441dbfdcea21f2554f0368d0a1adf and 8a08739.

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

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

  • src/v0/destinations/mp/util.js
  • src/v0/destinations/mp/util.test.js
🧬 Code Definitions (1)
src/v0/destinations/mp/util.js (1)
src/v0/destinations/mp/config.js (4)
  • MAX_NESTING_DEPTH (63-63)
  • MAX_PROPERTY_KEYS_COUNT (61-61)
  • MAX_ARRAY_ELEMENTS_COUNT (62-62)
  • MAX_PAYLOAD_SIZE_BYTES (64-64)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • 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: ingestion-service-test
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (7)
src/v0/destinations/mp/util.js (3)

46-89: Well-structured recursive validation implementation.

The implementation of the validateObjectRecursively function is clean, well-documented, and effectively validates objects against Mixpanel's limits. Each validation step is clear with appropriate error messages that include the path information.


207-209: Good integration of validation into the identify flow.

The validation call is placed at the right point in the workflow, ensuring properties are validated before constructing the payload.


504-504: Properly exported the new validation function.

The function has been correctly added to the module exports, making it available for external use.

src/v0/destinations/mp/util.test.js (4)

794-804: Good positive test case for valid properties.

The test correctly verifies that valid objects that conform to Mixpanel's limits don't throw errors. This is important for confirming the validation doesn't reject valid payloads.


806-817: Well-structured test for property limit validation.

The test dynamically creates an object that exceeds the property limit and confirms the validation function throws the expected error with the appropriate message.


872-879: Thorough handling of edge cases.

Testing with null, undefined, and non-object inputs ensures the validation function properly handles all possible inputs gracefully.


899-933: Comprehensive test for nested object validation.

The test cases for complex nested objects effectively verify both valid and invalid nested structures, ensuring the recursive validation works correctly at all nesting levels.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

sonarqubecloud Bot commented Apr 4, 2025

Copy link
Copy Markdown

@koladilip
koladilip merged commit bad8a67 into develop Apr 7, 2025
@koladilip
koladilip deleted the chore/add-validation-properties-length branch April 7, 2025 14:01
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