Skip to content

chore: fix status in mailchimp, fix cognitive complexity, add unit tests - #4314

Merged
yashasvibajpai merged 5 commits into
developfrom
chore.mchimp.bugsnag
May 15, 2025
Merged

yashasvibajpai merged 5 commits into
developfrom
chore.mchimp.bugsnag

Conversation

@yashasvibajpai

@yashasvibajpai yashasvibajpai commented May 12, 2025 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

This pull request refactors and improves the subscription status determination logic in the Mailchimp integration by introducing a new helper function, determineSubscriptionStatus, and simplifying the processPayload function. Additionally, it includes a minor fix to enhance code robustness.

Refactoring and Code Simplification:

  • Introduced a new helper function, determineSubscriptionStatus, to centralize and streamline the logic for determining a user's subscription status. This function handles both new and existing users, leveraging the checkIfDoubleOptIn and overrideSubscriptionStatus functions. (src/v0/destinations/mailchimp/utils.js, src/v0/destinations/mailchimp/utils.jsR314-R347)
  • Refactored the processPayload function to replace inline subscription status logic with a call to the new determineSubscriptionStatus helper function, improving readability and maintainability. (src/v0/destinations/mailchimp/utils.js, src/v0/destinations/mailchimp/utils.jsL361-R402)

Code Robustness:

  • Updated the error handling in the checkIfDoubleOptIn function to safely access the status property using optional chaining (error?.status), preventing potential runtime errors. (src/v0/destinations/mailchimp/utils.js, src/v0/destinations/mailchimp/utils.jsL216-R216)

What is the related Linear task?

Resolves INT-3652

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.

@yashasvibajpai
yashasvibajpai requested a review from koladilip May 12, 2025 23:41
@yashasvibajpai
yashasvibajpai requested a review from a team as a code owner May 12, 2025 23:41
@yashasvibajpai
yashasvibajpai requested a review from manish339k May 12, 2025 23:41
@coderabbitai

coderabbitai Bot commented May 12, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling to prevent runtime errors when processing subscription status for Mailchimp users.
  • Refactor

    • Streamlined the logic for determining subscription status, enhancing code modularity and maintainability.
  • Tests

    • Added comprehensive tests for Mailchimp utility functions, ensuring correct payload processing, error handling, and data transformation for various user scenarios.

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling to prevent runtime errors during Mailchimp subscription status checks.
  • Refactor

    • Streamlined logic for determining subscription status, enhancing code modularity and maintainability.
  • Tests

    • Introduced comprehensive tests for Mailchimp utility functions, ensuring correct behavior and robust error handling across various scenarios.

Walkthrough

The changes introduce a new helper function to encapsulate the logic for determining Mailchimp subscription status, refactor the main payload processing function for clarity, and add a comprehensive test suite for Mailchimp utility functions. The update also includes safer error handling and removes an unused variable assignment.

Changes

File(s) Change Summary
src/v0/destinations/mailchimp/utils.js Introduced determineSubscriptionStatus helper to centralize subscription status logic. Refactored processPayload to use this helper. Improved error handling by using optional chaining. Removed an unused variable assignment.
src/v0/destinations/mailchimp/utils.test.js Added a new test suite covering utility functions: audience ID retrieval, endpoint construction, property stringification, batch payload generation, and comprehensive scenarios for payload processing and subscription status determination.

Sequence Diagram(s)

sequenceDiagram
    participant Message
    participant Utils
    participant MailchimpAPI

    Message->>Utils: processPayload(message, config, audienceId, metadata)
    Utils->>MailchimpAPI: Check if user exists (GET)
    MailchimpAPI-->>Utils: User status or not found
    alt User does not exist
        Utils->>MailchimpAPI: Check double opt-in setting (GET)
        MailchimpAPI-->>Utils: Double opt-in enabled/disabled
        Utils->>Utils: Set status to 'pending' or 'subscribed'
    else User exists
        Utils->>Utils: Use overrideSubscriptionStatus if provided
    end
    Utils-->>Message: Return processed payload
Loading

Suggestions for Improvements

  • Consider extracting Mailchimp API interaction logic into a separate service layer to further decouple business logic from external dependencies.
  • Enhance error logging for API failures to aid in debugging and monitoring.
  • Expand test coverage to include negative cases and edge conditions for all utility functions, ensuring robust error handling.
  • Document the new helper function and its expected inputs/outputs for easier onboarding and maintenance.

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f2896de and 5e9bdf5.

📒 Files selected for processing (1)
  • src/v0/destinations/mailchimp/utils.test.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/v0/destinations/mailchimp/utils.test.js
🧬 Code Graph Analysis (1)
src/v0/destinations/mailchimp/utils.test.js (3)
src/v0/destinations/mailchimp/utils.js (10)
  • md5 (2-2)
  • email (357-357)
  • getAudienceId (112-122)
  • mailChimpSubscriptionEndpoint (62-63)
  • mailchimpEventsEndpoint (65-66)
  • stringifyPropertiesValues (96-104)
  • events (419-419)
  • generateBatchedPaylaodForArray (414-449)
  • metadata (417-417)
  • processPayload (355-406)
src/v0/util/constant.js (1)
  • JSON_MIME_TYPE (11-11)
src/constants/index.js (1)
  • MappedToDestinationKey (49-49)
⏰ 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 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 (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (13)
src/v0/destinations/mailchimp/utils.test.js (13)

17-20: Well-structured mock setup for dependencies

The mocks for network adapters and MD5 hashing are properly set up with appropriate implementation for isolated testing.


24-24: Great practice: clearing mocks between tests

Using jest.clearAllMocks() in the beforeEach block ensures a clean testing environment for each test case.


27-79: Good use of data-driven testing patterns

The test cases for getAudienceId use a clean, maintainable approach with a table of test cases and expectations, making it easy to add more test scenarios in the future.


81-109: Thorough endpoint construction verification

The tests for both subscription and events endpoints properly verify URL construction and MD5 hashing of email addresses.


111-149: Comprehensive property stringification testing

Tests cover both string and non-string values, ensuring the utility correctly handles different data types.


151-208: Complete batch payload generation test

The test verifies all aspects of the batch payload: members array, update_existing flag, endpoint construction, headers, and metadata preservation.

Note: There's a typo in the function name generateBatchedPaylaodForArray (should be "Payload" instead of "Paylaod"), but this is likely in the implementation file rather than an issue in the test file.


210-276: Well-implemented HTTP request mocking

The mock implementation elegantly handles different API response scenarios based on URL paths, simulating various Mailchimp API behaviors needed for testing.


278-420: Comprehensive payload processing test suite

Tests cover all critical scenarios: existing users, new users with different double opt-in configurations, custom subscription statuses, and reverse ETL sources. Each scenario properly verifies the expected output structure.


423-522: Excellent focus on subscription status determination

This test suite directly aligns with the PR's objective of introducing the new determineSubscriptionStatus helper function. The parameterized approach tests all key scenarios for status determination logic.


524-571: Good error handling verification

Properly tests how network errors from the Mailchimp API are handled and propagated.


573-614: Validates subscription status validation

This test confirms that invalid subscription statuses are properly rejected with appropriate error messages, ensuring data quality.


212-212: Excellent fix for mock call counting

The explicit handleHttpRequest.mockClear() call addresses a previous review comment that identified potential test pollution between test cases.


202-202: Security-conscious test assertion

Using expect.stringContaining('Basic ') avoids hard-coding full authentication credentials in the test file while still verifying the correct format.

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

@yashasvibajpai
yashasvibajpai requested a review from Copilot May 12, 2025 23:43

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refactors the Mailchimp integration by centralizing subscription status logic into a new helper function and improving error handling, while also adding unit tests to validate these changes.

  • Introduced the determineSubscriptionStatus helper function to simplify subscription status determination.
  • Refactored processPayload to use the new helper and improved error handling with optional chaining in checkIfDoubleOptIn.
Comments suppressed due to low confidence (1)

src/v0/destinations/mailchimp/utils.js:365

  • The removal of the email extraction line results in the email variable not being defined when passed to checkIfMailExists. Please reintroduce the assignment to ensure email is properly extracted from primaryPayload.
    -    email = get(primaryPayload, 'email_address');

@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 (2)
src/v0/destinations/mailchimp/utils.js (2)

214-220: Consider surfacing the actual HTTP status instead of defaulting to 400

error?.status || 400 swallows the real status code if error is defined but status is 0/null/undefined. When Mailchimp returns a 4xx or 5xx status, propagating that exact value provides more actionable telemetry and makes getDynamicErrorType mapping more precise.

-const status = error?.status || 400;
+const status = isDefinedAndNotNull(error?.status) ? error.status : 400;

This still guards against an undefined error object while preserving legitimate status codes.


314-346: Avoid redundant network calls by caching the double-opt-in flag

determineSubscriptionStatus fetches the list settings (checkIfDoubleOptIn) every time it is invoked for a new user.
If your batch contains many new users for the same list, this results in N identical HTTP GETs to /lists/{audienceId} which can quickly dominate latency and rate-limit budgets.

A lightweight optimisation:

+// cache scoped to this process; key = `${datacenterId}_${audienceId}`
+const doubleOptInCache = new Map();

...
-    const isDoubleOptin = await checkIfDoubleOptIn(apiKey, datacenterId, audienceId, metadata);
+    let isDoubleOptin = doubleOptInCache.get(audienceId);
+    if (isDoubleOptin === undefined) {
+      isDoubleOptin = await checkIfDoubleOptIn(apiKey, datacenterId, audienceId, metadata);
+      doubleOptInCache.set(audienceId, isDoubleOptin);
+    }

This preserves behaviour while cutting extraneous calls.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f368f00 and aac08d0.

📒 Files selected for processing (2)
  • src/v0/destinations/mailchimp/utils.js (3 hunks)
  • src/v0/destinations/mailchimp/utils.test.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/v0/destinations/mailchimp/utils.js
  • src/v0/destinations/mailchimp/utils.test.js
🧬 Code Graph Analysis (1)
src/v0/destinations/mailchimp/utils.test.js (3)
src/v0/destinations/mailchimp/utils.js (12)
  • md5 (2-2)
  • email (357-357)
  • getAudienceId (112-122)
  • mailChimpSubscriptionEndpoint (62-63)
  • mailchimpEventsEndpoint (65-66)
  • stringifyPropertiesValues (96-104)
  • events (419-419)
  • generateBatchedPaylaodForArray (414-449)
  • metadata (417-417)
  • processPayload (355-406)
  • userStatus (152-155)
  • userStatus (392-392)
src/v0/util/constant.js (1)
  • JSON_MIME_TYPE (11-11)
src/constants/index.js (1)
  • MappedToDestinationKey (49-49)
⏰ 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 ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)

@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:

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@yashasvibajpai
yashasvibajpai requested a review from ItsSudip May 13, 2025 04:40
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented May 15, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.12%. Comparing base (7f558ad) to head (a4e67a9).
Report is 8 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4314      +/-   ##
===========================================
- Coverage    91.32%   91.12%   -0.21%     
===========================================
  Files          636      636              
  Lines        33381    33382       +1     
  Branches      7891     7888       -3     
===========================================
- Hits         30486    30418      -68     
- Misses        2650     2725      +75     
+ Partials       245      239       -6     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sonarqubecloud

Copy link
Copy Markdown

@yashasvibajpai
yashasvibajpai merged commit 8948a89 into develop May 15, 2025
@yashasvibajpai
yashasvibajpai deleted the chore.mchimp.bugsnag branch May 15, 2025 04:35
ItsSudip pushed a commit that referenced this pull request May 15, 2025
…sts (#4314)

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

* chore: fix PR comments for mailchimp tests

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

---------

Co-authored-by: Dilip Kola <[email protected]>
ItsSudip added a commit that referenced this pull request May 27, 2025
* feat: update destination type with optional account types (#4291)

* feat: update destination type with optional account types

* chore: add authenticationType

* chore: update types with generics

* chore: add optional config to accountDefiition

* chore: update deleteAccount to regulationAccount

* chore: update regulationAccount to deleteAccount

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

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

* refactor: tests to use proper types

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

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

* chore: fix PR comments for mailchimp tests

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

---------

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

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

* chore(braze): added docs for braze destination

* chore: update braze docs

* chore: add multiplexing section

---------

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

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

* chore: add string check for phone in gaoc

* chore: add unit test

* chore: update condition

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

---------

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

* chore: correct dotenv import (#4320)

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

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

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

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

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

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

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

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

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

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

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

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

* chore: mp add content type header to all apis

* feat: bluecore email subscription event (#4304)

* fix: blucore optin event mapping

* fix: review comments

* chore: add subscription event

* chore: add subscription event

* fix: reviews comments

* fix: review comments

* fix: review comments

* fix: review comments

* chore: test description

* chore(release): 1.101.0

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

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

This reverts commit f368f00.

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: Sudip Paul <[email protected]>
Co-authored-by: Yashasvi Bajpai <[email protected]>
Co-authored-by: Dilip Kola <[email protected]>
Co-authored-by: Dilip Kola <[email protected]>
Co-authored-by: Vinay Teki <[email protected]>
Co-authored-by: Utsab Chowdhury <[email protected]>
Co-authored-by: Aris Tzoumas <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Mahesh Kutty <[email protected]>
Co-authored-by: GitHub Actions <[email protected]>
Co-authored-by: Jayachand Mopidevi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants