Skip to content

fix(campaign_manager): handling normalizePhone function error - #4592

Merged
manish339k merged 2 commits into
developfrom
fix.campaign_manager.invalid.phone
Sep 2, 2025
Merged

manish339k merged 2 commits into
developfrom
fix.campaign_manager.invalid.phone

Conversation

@manish339k

@manish339k manish339k commented Aug 27, 2025 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

Add proper error handling for invalid phone numbers in Campaign Manager normalizePhone function

Note: This will not solve the actual integration issue. We will handle it seperately.

Problem

The normalizePhone function was throwing unhandled 500 error (because of parsePhoneNumber was throwing unhandled INVALID_COUNTRY errors from libphonenumber-js) for invalid phone numbers instead of throwing proper 400 errors.

Solution

Added proper error handling to ensure the function always either returns a valid E.164 formatted phone number or throws an InstrumentationError.

Changes

  • Added missing throw new InstrumentationError('Invalid phone number') for invalid cases
  • Function now consistently handles all error scenarios instead of returning undefined

Impact

  • Low risk: Only affects error handling, no functional changes
  • High value: Improves data quality and error reporting

This ensures the Campaign Manager destination properly validates phone numbers and provides clear error messages when normalization fails, improving overall data integrity.

What is the related Linear task?

Resolves INT-4069

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.

@manish339k
manish339k requested a review from a team as a code owner August 27, 2025 11:13
@coderabbitai

coderabbitai Bot commented Aug 27, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • None.
  • Bug Fixes

    • Improved phone number validation to provide clearer error messages when numbers are invalid or cannot be parsed, enhancing reliability for users entering phone details.
  • Tests

    • Added coverage to ensure errors are correctly raised when the country code is missing or invalid during phone number normalization.

Walkthrough

normalizePhone now wraps phone parsing/validation in a try/catch and throws an InstrumentationError containing the original parse error message on failure. A unit test was added to assert the detailed error when countryCode is null.

Changes

Cohort / File(s) Summary
Campaign Manager util
src/v0/destinations/campaign_manager/util.js
Added try/catch around phone parsing; on parse failure or invalid number it now throws InstrumentationError('Invalid phone number with error: ${error}') instead of a plain generic throw. No public signatures changed.
Campaign Manager tests
src/v0/destinations/campaign_manager/util.test.js
Added a test asserting normalizePhone throws InstrumentationError with message Invalid phone number with error: ParseError: INVALID_COUNTRY when countryCode is null.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant util as normalizePhone
  participant lib as parsePhoneNumber
  Note over Caller,util #E8F0FE: New flow adds try/catch and propagates parse errors

  Caller->>util: normalizePhone(input, countryCode)
  util->>lib: parsePhoneNumber(input, countryCode)
  alt parse succeeds and is valid
    lib-->>util: PhoneNumber object
    util-->>Caller: return phoneNumber.format('E.164')
  else parse fails or invalid
    lib-->>util: throws ParseError
    util-->>util: catch error
    util-->>Caller: throw InstrumentationError("Invalid phone number with error: " + error)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • sivashanmukh
  • vinayteki95

Suggestions:

  • Add tests for valid numbers with and without explicit countryCode across a few regions.
  • Audit callers to ensure they correctly handle InstrumentationError messages if they depended on the previous generic error.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix.campaign_manager.invalid.phone

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.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit 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:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@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 (3)
src/v0/destinations/campaign_manager/util.test.js (2)

58-64: Stabilize the assertion; avoid depending on libphonenumber-js error wording

Asserting the full vendor error text is brittle across versions. Match the invariant part of the message instead.

-    expect(() => normalizePhone(invalidPhone, countryCode)).toThrow(
-      'Invalid phone number with error: ParseError: INVALID_COUNTRY',
-    );
+    expect(() => normalizePhone(invalidPhone, countryCode)).toThrow(/Invalid phone number/);

1-1: Remove unused import (ESLint: no-unused-vars)

sha256 isn’t used in this test file.

-const sha256 = require('sha256');
src/v0/destinations/campaign_manager/util.js (1)

56-64: Don’t double-wrap errors; return a consistent message

Currently, throwing InstrumentationError('Invalid phone number') inside try is caught and re-wrapped as "Invalid phone number with error: InstrumentationError: Invalid phone number". This is noisy and couples tests to library error strings. Prefer preserving existing InstrumentationError and emitting a stable message for other errors.

   } catch (error) {
-    throw new InstrumentationError(`Invalid phone number with error: ${error}`);
+    if (error instanceof InstrumentationError) {
+      throw error; // already normalized
+    }
+    throw new InstrumentationError('Invalid phone number');
   }

Note: If you adopt this, update the new test to assert a substring (e.g., /Invalid phone number/) rather than the full vendor message.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 55a664f and b22a642.

📒 Files selected for processing (2)
  • src/v0/destinations/campaign_manager/util.js (2 hunks)
  • src/v0/destinations/campaign_manager/util.test.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v0/destinations/campaign_manager/util.test.js
  • src/v0/destinations/campaign_manager/util.js
🧬 Code graph analysis (1)
src/v0/destinations/campaign_manager/util.test.js (1)
src/v0/destinations/campaign_manager/util.js (1)
  • normalizePhone (55-65)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (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 (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
src/v0/destinations/campaign_manager/util.js (1)

100-100: All normalizeAndHash call sites verified
I’ve inspected every normalizeAndHash( invocation across the repo. Only the hashedPhoneNumber call in src/v0/destinations/campaign_manager/util.js (lines 98–101) passes an options object—and it correctly includes { countryCode: payload.addressInfo?.countryCode }. No other calls supply an options shape, so this change is isolated and ready to merge.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@manish339k
manish339k requested a review from a team August 29, 2025 05:29
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@manish339k
manish339k force-pushed the fix.campaign_manager.invalid.phone branch from 4b4fb2e to 5a3b888 Compare August 29, 2025 05:35

@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/campaign_manager/util.test.js (2)

58-64: Make the assertion resilient and fix test name grammar

Avoid coupling to libphonenumber-js’s exact error string; assert a stable pattern instead and tighten the test title wording.

-  it('should throw an InstrumentationError when the phone number is with invalid country code', () => {
+  it('should throw an InstrumentationError when the country code is invalid', () => {
     const invalidPhone = '1234567890';
     const countryCode = null;
-    expect(() => normalizePhone(invalidPhone, countryCode)).toThrow(
-      'Invalid phone number with error: ParseError: INVALID_COUNTRY',
-    );
+    expect(() => normalizePhone(invalidPhone, countryCode)).toThrow(
+      /Invalid phone number with error: .*INVALID_COUNTRY/,
+    );
   });

58-64: Broaden coverage with a small table-driven test

Consider covering a few invalid-country scenarios (null, undefined, empty string, and an invalid ISO code) to prevent regressions.

it.each([
  ['null country', null],
  ['undefined country', undefined],
  ['empty country', ''],
  ['invalid ISO', 'ZZ'],
])('should throw for %s', (_label, cc) => {
  expect(() => normalizePhone('1234567890', cc)).toThrow(/Invalid phone number/);
});
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4b4fb2e and 5a3b888.

⛔ Files ignored due to path filters (1)
  • test/integrations/destinations/campaign_manager/processor/data.ts is excluded by !**/test/**
📒 Files selected for processing (2)
  • src/v0/destinations/campaign_manager/util.js (1 hunks)
  • src/v0/destinations/campaign_manager/util.test.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/v0/destinations/campaign_manager/util.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v0/destinations/campaign_manager/util.test.js
🧬 Code graph analysis (1)
src/v0/destinations/campaign_manager/util.test.js (1)
src/v0/destinations/campaign_manager/util.js (1)
  • normalizePhone (55-65)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • 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/v0/destinations/campaign_manager/util.test.js (1)

58-64: Investigate error class and function definitions
Running searches for InstrumentationError yielded no references in the repo, and normalizePhone appears in src/v0/destinations/campaign_manager/util.js. Since the error class isn’t locally defined or exported, you can’t import it in tests. Keep the existing message assertion only.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@rudderlabs rudderlabs deleted a comment from codecov Bot Sep 1, 2025
@maheshkutty maheshkutty closed this Sep 1, 2025
@maheshkutty maheshkutty reopened this Sep 1, 2025
@codecov

codecov Bot commented Sep 1, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.79%. Comparing base (e9a4ebd) to head (5a3b888).
⚠️ Report is 10 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #4592   +/-   ##
========================================
  Coverage    91.79%   91.79%           
========================================
  Files          642      642           
  Lines        33928    33930    +2     
  Branches      8040     8040           
========================================
+ Hits         31143    31145    +2     
- Misses        2533     2555   +22     
+ Partials       252      230   -22     

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

@sonarqubecloud

sonarqubecloud Bot commented Sep 1, 2025

Copy link
Copy Markdown

@manish339k
manish339k merged commit cb5b92e into develop Sep 2, 2025
@manish339k
manish339k deleted the fix.campaign_manager.invalid.phone branch September 2, 2025 05:25
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