Skip to content

fix: add validation for null/undefined traits - #4684

Merged
ItsSudip merged 2 commits into
developfrom
fix/sendinBlue
Sep 29, 2025
Merged

ItsSudip merged 2 commits into
developfrom
fix/sendinBlue

Conversation

@ItsSudip

Copy link
Copy Markdown
Member

Add validation for null/undefined traits in Sendinblue (Brevo) destination

What are the changes introduced in this PR?

  • Add input validation in transformUserTraits to throw a clear error when traits is undefined (null/undefined), preventing runtime crashes during track processing.
  • Minor refactor in transformUserTraits loop style for clarity while preserving behavior for valid inputs.

Changed files:

  • src/v0/destinations/sendinblue/util.js

What is the related Linear task?

Please explain the objectives of your changes below

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

  • Before: Track payloads could reach trait transformation with traits undefined, leading to runtime errors (e.g., “Cannot convert undefined or null to object”) deeper in the flow.
  • Now: We fail fast with a clear, actionable error when traits is not provided to transformUserTraits. This avoids obscure transformation crashes and ensures consistent error semantics.

Impact:

  • Track events that previously crashed due to undefined traits will now abort with a deterministic validation error.
  • No change to normal flows: valid objects and empty objects behave as before; only undefined/null inputs are rejected.

Any new dependencies introduced with this change?

  • None.

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

  • Updated transformUserTraits(traits, contactAttributeMapping):
    • Throws InstrumentationError('Sendinblue: traits should be defined.') if traits is undefined.
    • Retains mapping logic and removal of original keys via refineUserTraits.

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

  • Negligible performance impact; validation is O(1) and executed only once per transform call.
  • Error messages are explicit, aiding faster debugging and reducing retries.

@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? (Linear card)
  • All changes manually tested?
  • Any documentation changes needed with this change? (N/A)
  • Is the PR limited to 10 file changes? (Yes)
  • Is the PR limited to one linear task? (Yes)
  • Are relevant unit and component test-cases added in new readability format? (N/A in this diff; behavior is a guarded validation; integration tests unaffected)

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.

@ItsSudip
ItsSudip requested a review from a team as a code owner September 26, 2025 09:21
@coderabbitai

coderabbitai Bot commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation for Sendinblue user trait syncing: clear error when traits are missing.
    • More robust handling of empty inputs and falsy values while preserving other traits and mapping behavior.
  • Tests

    • Added comprehensive tests for user trait transformation, covering mapping and key removal, ignoring empty/falsy values, empty input behavior, and validation error handling.

Walkthrough

Adds validation so transformUserTraits throws when traits are undefined, refactors the attribute mapping loop to a for-of iteration, and adds tests covering mapping, omission of falsy values, empty input, and the validation error.

Changes

Cohort / File(s) Summary
Sendinblue util & tests
src/v0/destinations/sendinblue/util.js, src/v0/destinations/sendinblue/util.test.js
util.js: require defined traits (throw InstrumentationError if undefined), replace attribute-mapping iteration with a for...of loop, preserve refineUserTraits call and return. util.test.js: new tests for mapping & removal of original keys, ignoring falsy values, empty-object input, and throwing on undefined traits.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant Util as transformUserTraits
  participant Refiner as refineUserTraits

  Caller->>Util: transformUserTraits(traits, config)
  alt traits is undefined
    Util-->>Caller: throw InstrumentationError("Sendinblue: traits should be defined.")
  else traits defined
    note right of Util #DDEEFF: map configured keys\n(using for...of over attribute map)
    Util->>Util: map traits per contactAttributeMapping\n(remove original keys, omit falsy)
    Util->>Refiner: refineUserTraits(mappedTraits)
    Refiner-->>Util: refinedTraits
    Util-->>Caller: refinedTraits
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggestions

  • Validate contactAttributeMapping entries (ensure from and to exist and are strings) to avoid runtime issues.
  • Add tests for non-string trait values, nested objects, and boundary cases (e.g., arrays) to confirm omission and mapping behavior.
  • Include an explicit unit test asserting the exact InstrumentationError type and message to prevent regressions.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title “fix: add validation for null/undefined traits” clearly and concisely summarizes the main change by indicating that the pull request adds input validation for null or undefined traits, matching the core modification in the util.js file without extraneous details.
Description Check ✅ Passed The description closely follows the repository’s template by providing sections for the change summary, related Linear task, detailed objectives (including behavior changes, dependencies, utilities, and performance considerations), and both developer and reviewer checklists, ensuring all required information is present and clearly organized.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ 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/sendinBlue

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (4)
src/v0/destinations/sendinblue/util.js (3)

123-125: Prefer explicit null/undefined check for intent clarity.

Use a nullish check rather than generic falsy to match the stated requirement.

Apply this diff:

-  if (!userTraits) {
+  if (userTraits == null) {
     throw new InstrumentationError('Sendinblue: traits should be defined.');
   }

Based on learnings


126-131: Avoid dropping valid falsy trait values (0/false).

Current truthy check skips 0/false. If those should map through, use an explicit emptiness check.

Apply this diff:

-  for (const key of Object.keys(attributeMap)) {
-    const traitValue = traits[key];
-    if (traitValue) {
-      userTraits[attributeMap[key]] = traitValue;
-    }
-  }
+  for (const key of Object.keys(attributeMap)) {
+    const traitValue = traits[key];
+    if (traitValue !== undefined && traitValue !== null && traitValue !== '') {
+      userTraits[attributeMap[key]] = traitValue;
+    }
+  }

If Sendinblue attributes should omit only empty/null values but allow 0/false, this change is appropriate. Please confirm expected semantics. Based on learnings


121-121: Optional: avoid mutating the caller’s traits object.

A shallow copy prevents side effects to inputs. If backward compatibility permits, consider copying.

Apply this diff:

-  const userTraits = traits;
+  const userTraits = { ...traits };

Based on learnings

src/v0/destinations/sendinblue/util.test.js (1)

32-36: Add a test for null traits as well.

You cover undefined; include null to reflect the requirement.

Apply this diff:

   test('throws when traits is undefined', () => {
     expect(() => transformUserTraits(undefined, contactAttributeMapping)).toThrow(
       'Sendinblue: traits should be defined.',
     );
   });
+
+  test('throws when traits is null', () => {
+    expect(() => transformUserTraits(null, contactAttributeMapping)).toThrow(
+      'Sendinblue: traits should be defined.',
+    );
+  });

Based on learnings

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 34d0938 and 0c48db8.

📒 Files selected for processing (2)
  • src/v0/destinations/sendinblue/util.js (1 hunks)
  • src/v0/destinations/sendinblue/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/sendinblue/util.test.js
  • src/v0/destinations/sendinblue/util.js
🧠 Learnings (1)
📓 Common learnings
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4589
File: scripts/common.ts:74-78
Timestamp: 2025-08-28T15:39:08.293Z
Learning: User ItsSudip prefers simpler solutions over complex edge case handling, especially when the simpler approach is sufficient for the actual use case.
🧬 Code graph analysis (2)
src/v0/destinations/sendinblue/util.test.js (1)
src/v0/destinations/sendinblue/util.js (7)
  • require (1-1)
  • require (3-3)
  • require (4-10)
  • require (11-11)
  • require (12-15)
  • require (17-17)
  • transformUserTraits (117-134)
src/v0/destinations/sendinblue/util.js (1)
src/v0/destinations/sendinblue/transform.js (3)
  • userTraits (101-104)
  • userTraits (139-139)
  • userTraits (243-246)
⏰ 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). (7)
  • 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: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
src/v0/destinations/sendinblue/util.test.js (3)

9-17: LGTM: mapping + removal covered.

Covers key rename and cleanup correctly.


19-24: LGTM: falsy value behavior captured.

Matches current implementation (skips '', null).


26-30: LGTM: empty object case validated.

Confirms empty object passes through unchanged, consistent with code.

src/v0/destinations/sendinblue/util.js (1)

117-134: No issues with transformUserTraits call sites
All invocations in sendinblue/transform.js use payload.attributes or payload.properties from constructPayload, which always yields an object (defaulting to {}). The new fail-fast check won’t trigger unexpectedly.

Comment thread src/v0/destinations/sendinblue/util.js Resolved
@codecov

codecov Bot commented Sep 26, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.79%. Comparing base (c0e7bda) to head (67f217c).
⚠️ Report is 6 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #4684   +/-   ##
========================================
  Coverage    91.79%   91.79%           
========================================
  Files          642      642           
  Lines        33998    34007    +9     
  Branches      8035     8044    +9     
========================================
+ Hits         31207    31216    +9     
+ Misses        2561     2539   -22     
- Partials       230      252   +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:

ItsSudip and others added 2 commits September 29, 2025 09:54
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@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 (1)
src/v0/destinations/sendinblue/util.js (1)

122-125: Tighten null/undefined check and add null unit test

Replace the loose falsy guard with an explicit null/undefined check:

-  if (!userTraits) {
+  if (userTraits === null || userTraits === undefined) {
     throw new InstrumentationError('Sendinblue: traits should be defined.');
   }

Add a unit test for null:

test('throws when traits is null', () => {
  expect(() =>
    transformUserTraits(null, contactAttributeMapping)
  ).toThrow('Sendinblue: traits should be defined.');
});

Optional: move this validation just before destructuring/aliasing for clarity.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2920210 and 67f217c.

📒 Files selected for processing (2)
  • src/v0/destinations/sendinblue/util.js (1 hunks)
  • src/v0/destinations/sendinblue/util.test.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/v0/destinations/sendinblue/util.test.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/sendinblue/util.js
🧠 Learnings (1)
📓 Common learnings
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4589
File: scripts/common.ts:74-78
Timestamp: 2025-08-28T15:39:08.293Z
Learning: User ItsSudip prefers simpler solutions over complex edge case handling, especially when the simpler approach is sufficient for the actual use case.
🧬 Code graph analysis (1)
src/v0/destinations/sendinblue/util.js (1)
src/v0/destinations/sendinblue/transform.js (3)
  • userTraits (101-104)
  • userTraits (139-139)
  • userTraits (243-246)
⏰ 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 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: 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: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
src/v0/destinations/sendinblue/util.js (1)

126-131: Loop refactor LGTM; behavior preserved.

Iterating Object.keys(attributeMap) with a for...of retains the original semantics and keeps the mapping logic clear. No issues found.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

Comment thread src/v0/destinations/sendinblue/util.js Resolved
@sonarqubecloud

Copy link
Copy Markdown

@ItsSudip
ItsSudip merged commit f909a8f into develop Sep 29, 2025
@ItsSudip
ItsSudip deleted the fix/sendinBlue branch September 29, 2025 04:56
ItsSudip added a commit that referenced this pull request Sep 29, 2025
krishna2020 pushed a commit that referenced this pull request Sep 29, 2025
Revert "fix: add validation for null/undefined traits (#4684)"

This reverts commit f909a8f.
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.

3 participants