Repository navigation
fix: add mapping of event_source instead of static value - #4497
Conversation
Summary by CodeRabbit
WalkthroughDynamic event_source detection and per-source batching were added to the TikTok Ads transformer; payloads are enriched with content-level fields, device identifiers are sanitized based on OS, test events are separated, processed events are grouped/batched per resolved event_source, and final responses are deterministically ordered by jobId. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant TransformV2
participant Util
Client->>TransformV2: Send event message
TransformV2->>Util: getEventSource(message)
Util-->>TransformV2: resolved event_source
TransformV2->>TransformV2: Enrich properties.contents with contents_ids, num_items (if present)
TransformV2->>TransformV2: Sanitize user IDs based on OS (remove idfa/idfv/gaid accordingly)
TransformV2->>TransformV2: separateTestEvents(...) -> separate test vs regular events
TransformV2->>TransformV2: Group processedEvents by event_source
TransformV2->>TransformV2: batchEvents(processedEventsGroup, event_source) -> buildResponseList(...)
TransformV2-->>Client: Return ordered list of batched responses + test events + errors (sorted by jobId)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~35 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Suggestions for improvement
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 unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
test/integrations/destinations/tiktok_ads/router/data.tsis excluded by!**/test/**
📒 Files selected for processing (3)
src/v0/destinations/tiktok_ads/transformV2.js(4 hunks)src/v0/destinations/tiktok_ads/util.js(1 hunks)src/v0/destinations/tiktok_ads/util.test.js(2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js
Instructions used from:
Sources:
⚙️ CodeRabbit Configuration File
🧠 Learnings (4)
📓 Common learnings
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4380
File: src/v0/destinations/google_adwords_remarketing_lists/config.js:3-5
Timestamp: 2025-06-04T07:24:58.591Z
Learning: User maheshkutty prefers to handle Google Ads API version upgrades for different destinations in separate pull requests rather than bundling multiple destinations together in a single PR.
Learnt from: krishna2020
PR: rudderlabs/rudder-transformer#4178
File: src/sources/shopify/transform.js:37-45
Timestamp: 2025-03-21T12:32:28.443Z
Learning: The getBodyFromV2SpecPayload function in Shopify source transformation throws an error if request is not defined, making additional null checks in getEventFromV2Request function unnecessary.
src/v0/destinations/tiktok_ads/util.test.js (1)
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.
src/v0/destinations/tiktok_ads/transformV2.js (5)
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Learnt from: krishna2020
PR: rudderlabs/rudder-transformer#4178
File: src/sources/shopify/transform.js:37-45
Timestamp: 2025-03-21T12:32:28.443Z
Learning: The getBodyFromV2SpecPayload function in Shopify source transformation throws an error if request is not defined, making additional null checks in getEventFromV2Request function unnecessary.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4380
File: src/v0/destinations/google_adwords_remarketing_lists/config.js:3-5
Timestamp: 2025-06-04T07:24:58.591Z
Learning: User maheshkutty prefers to handle Google Ads API version upgrades for different destinations in separate pull requests rather than bundling multiple destinations together in a single PR.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4364
File: src/v0/util/index.js:2220-2242
Timestamp: 2025-06-02T06:25:17.338Z
Learning: In the rudderlabs/rudder-transformer codebase, jobId values are guaranteed by system contract to always be valid numbers and never undefined or infinite. Additional validation for these edge cases in sorting functions like sortBatchesByMinJobId is not necessary.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.
src/v0/destinations/tiktok_ads/util.js (2)
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Learnt from: krishna2020
PR: rudderlabs/rudder-transformer#4178
File: src/sources/shopify/transform.js:37-45
Timestamp: 2025-03-21T12:32:28.443Z
Learning: The getBodyFromV2SpecPayload function in Shopify source transformation throws an error if request is not defined, making additional null checks in getEventFromV2Request function unnecessary.
🧬 Code Graph Analysis (2)
src/v0/destinations/tiktok_ads/util.test.js (1)
src/v0/destinations/tiktok_ads/util.js (2)
message(11-11)getEventSource(70-86)
src/v0/destinations/tiktok_ads/util.js (1)
src/v0/destinations/tiktok_ads/transformV2.js (1)
eventSource(686-686)
⏰ 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: test_and_publish
- GitHub Check: UT Tests
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Analyze (go)
🔇 Additional comments (3)
src/v0/destinations/tiktok_ads/util.js (1)
64-86: Well-implemented utility function with proper fallback logic.The
getEventSourcefunction correctly implements the precedence hierarchy (eventSource → channel → default) and includes appropriate null safety checks. The documentation clearly references the TikTok Business API documentation and the logic aligns with the supported event sources.src/v0/destinations/tiktok_ads/util.test.js (1)
176-209: Comprehensive test coverage for the getEventSource utility.The test suite effectively covers all critical scenarios including valid inputs, fallback behavior, edge cases, and precedence logic. The test cases are well-structured and provide good validation for the utility function.
src/v0/destinations/tiktok_ads/transformV2.js (1)
134-134: Correct implementation for single event transformation.The integration of
getEventSource(message)properly replaces the hardcoded'web'value with dynamic event source determination.
|
Allure Test reports for this run are available at:
|
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #4497 +/- ##
========================================
Coverage 91.79% 91.80%
========================================
Files 642 642
Lines 33889 33920 +31
Branches 8028 8039 +11
========================================
+ Hits 31110 31141 +31
- Misses 2527 2549 +22
+ Partials 252 230 -22 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
base branch main? |
I did it intentionally. We might need to do a hotfix. |
|
Allure Test reports for this run are available at:
|
3 similar comments
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
3d8823c to
94bc5be
Compare
|
Allure Test reports for this run are available at:
|
94bc5be to
fbe12e7
Compare
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
src/v0/destinations/tiktok_ads/transformV2.js (1)
798-805: Earlier “last-write-wins” event_source issue fixed by per-source groupingGrouping by event_source and passing it into batchEvents resolves the overwrite bug previously noted. Nice improvement.
Also applies to: 723-766
🧹 Nitpick comments (3)
src/v0/destinations/tiktok_ads/transformV2.js (3)
85-96: Harden OS checks to avoid type errors and improve robustnessGood OS-aware filtering. Minor safety: guard toLowerCase with a type check to avoid errors if os isn’t a string.
- if (isDefinedAndNotNull(os) && payload.user) { - if (isAppleFamily(os)) { + if (isDefinedAndNotNull(os) && payload.user) { + if (isAppleFamily(os)) { delete payload.user.gaid; - } else if (os.toLowerCase() === 'android') { + } else if (typeof os === 'string' && os.toLowerCase() === 'android') { delete payload.user.idfa; delete payload.user.idfv; } }
768-805: Typo and iteration style in grouping by event_source
- Rename pocessedEventsGroups → processedEventsGroups.
- Use Object.entries for clarity and fewer lookups.
- const pocessedEventsGroups = await groupByInBatches( + const processedEventsGroups = await groupByInBatches( processedEvents, (event) => event.message[0].body.JSON.event_source, ); - Object.keys(pocessedEventsGroups).forEach((eventSource) => { - batchedResponseList.push(...batchEvents(pocessedEventsGroups[eventSource], eventSource)); - }); + for (const [eventSource, group] of Object.entries(processedEventsGroups)) { + batchedResponseList.push(...batchEvents(group, eventSource)); + }
445-457: Docstring typos and clarityMinor typos: “proecessedEvents” → “processedEvents”, “metadat” → “metadata”. Consider tightening the description.
- * This clubs proecessedEvents request body and metadat based upon maxBatchSize + * This batches processedEvents (body and metadata) up to maxBatchSize
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between acf1d7b02845bdc8da2ddad01dedd94b54cb3762 and 691785a3ec24827fcf5ba7fa21e3fea9df269346.
📒 Files selected for processing (1)
src/v0/destinations/tiktok_ads/transformV2.js(11 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/tiktok_ads/transformV2.js
🧠 Learnings (4)
📓 Common learnings
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
📚 Learning: 2025-07-15T06:27:07.528Z
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
Applied to files:
src/v0/destinations/tiktok_ads/transformV2.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Applied to files:
src/v0/destinations/tiktok_ads/transformV2.js
📚 Learning: 2025-06-04T07:24:58.591Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4380
File: src/v0/destinations/google_adwords_remarketing_lists/config.js:3-5
Timestamp: 2025-06-04T07:24:58.591Z
Learning: User maheshkutty prefers to handle Google Ads API version upgrades for different destinations in separate pull requests rather than bundling multiple destinations together in a single PR.
Applied to files:
src/v0/destinations/tiktok_ads/transformV2.js
🧬 Code Graph Analysis (1)
src/v0/destinations/tiktok_ads/transformV2.js (3)
src/v0/destinations/tiktok_ads/util.js (2)
message(11-11)getEventSource(78-111)src/v0/destinations/tiktok_ads/config.js (1)
PARTNER_NAME(18-18)src/v0/util/index.js (8)
payload(1080-1080)get(14-14)message(1162-1162)message(1196-1196)getSuccessRespEvents(499-511)metadata(959-971)metadata(1986-1986)sortBatchesByMinJobId(2274-2279)
⏰ 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). (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 ARM64
- 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 (5)
src/v0/destinations/tiktok_ads/transformV2.js (5)
4-10: Imports updated appropriately for new batching and OS logicThe added utilities (groupByInBatches, get) and isAppleFamily/getEventSource support the new behavior. No issues.
Also applies to: 25-27
166-170: Dynamic event_source via getEventSource — LGTMCorrectly derives supported values with sensible defaults; matches PR goals.
436-443: Helper wrapper for batched responses — LGTMbuildResponseList composes batch responses correctly with batched=true.
409-420: Batch request builder — LGTMCorrect headers, endpoint, and body assignment for TikTok batch track API.
808-809: No action needed: error responses already use metadata arrays
I’ve confirmed thathandleRtTfSingleEventErrorcallsgetErrorRespEvents([input.metadata], …), so every entry inerrorRespListhas itsmetadatawrapped in an array as expected. The finalsortBatchesByMinJobIdcall can safely assumemetadatais always an array.
|
Allure Test reports for this run are available at:
|
6ce55ba to
a5e4405
Compare
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/v0/destinations/tiktok_ads/transformV2.js (1)
422-434: Fix array passing issue for test events.The code passes the entire message array to
getSuccessRespEventsinstead of the single request object, which could cause downstream issues.Apply this fix:
if (event.message[0].body.JSON.test_event_code) { - const { metadata, destination, message } = event; - processedTestEvents.push(getSuccessRespEvents(message, [metadata], destination)); + const { metadata, destination } = event; + processedTestEvents.push(getSuccessRespEvents(event.message[0], [metadata], destination)); } else {
🧹 Nitpick comments (1)
src/v0/destinations/tiktok_ads/transformV2.js (1)
723-766: Consider safer optional chaining and cleaner iteration pattern.The current implementation uses unsafe optional chaining and could benefit from more defensive programming.
Consider this safer approach:
- processedEvents.forEach((event) => { - const eventData = event.message[0]?.body.JSON.data; - // eslint-disable-next-line no-unsafe-optional-chaining, unicorn/consistent-destructuring - if (eventData?.length + data.length > config.maxBatchSizeV2) { + for (const event of processedEvents) { + const eventData = event.message[0]?.body?.JSON?.data; + const eventLen = Array.isArray(eventData) ? eventData.length : 0; + if (eventLen + data.length > config.maxBatchSizeV2) { responseLists.push( buildResponseList({ event: { event_source_id: pixelCode, event_source: eventSource, partner_name: PARTNER_NAME, data: [...data], }, metadata: [...metadata], destination, }), ); data = []; metadata = []; } - data.push(...eventData); + if (eventLen) data.push(...eventData); metadata.push(event.metadata); - }); + }
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 6ce55bac1648fb37e14f8aaf93da26a9e62a66de and a5e4405728c6701e315961879d776297b1325d2d.
⛔ Files ignored due to path filters (3)
src/v0/destinations/tiktok_ads/data/TikTokTrackV2.jsonis excluded by!**/*.jsontest/integrations/destinations/tiktok_ads/processor/data.tsis excluded by!**/test/**test/integrations/destinations/tiktok_ads/router/data.tsis excluded by!**/test/**
📒 Files selected for processing (4)
src/v0/destinations/tiktok_ads/transformV2.js(11 hunks)src/v0/destinations/tiktok_ads/transformV2.test.js(1 hunks)src/v0/destinations/tiktok_ads/util.js(2 hunks)src/v0/destinations/tiktok_ads/util.test.js(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/v0/destinations/tiktok_ads/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/tiktok_ads/transformV2.test.jssrc/v0/destinations/tiktok_ads/transformV2.jssrc/v0/destinations/tiktok_ads/util.test.js
🧠 Learnings (5)
📓 Common learnings
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
📚 Learning: 2025-07-15T06:27:07.528Z
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
Applied to files:
src/v0/destinations/tiktok_ads/transformV2.test.jssrc/v0/destinations/tiktok_ads/transformV2.jssrc/v0/destinations/tiktok_ads/util.test.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Applied to files:
src/v0/destinations/tiktok_ads/transformV2.js
📚 Learning: 2025-06-04T07:24:58.591Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4380
File: src/v0/destinations/google_adwords_remarketing_lists/config.js:3-5
Timestamp: 2025-06-04T07:24:58.591Z
Learning: User maheshkutty prefers to handle Google Ads API version upgrades for different destinations in separate pull requests rather than bundling multiple destinations together in a single PR.
Applied to files:
src/v0/destinations/tiktok_ads/transformV2.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.
Applied to files:
src/v0/destinations/tiktok_ads/transformV2.js
🧬 Code Graph Analysis (3)
src/v0/destinations/tiktok_ads/transformV2.test.js (3)
src/v0/destinations/tiktok_ads/util.js (1)
message(11-11)src/v0/destinations/tiktok_ads/transformV2.js (4)
config(28-28)config(30-36)trackResponseBuilder(108-173)data(725-725)src/v0/destinations/tiktok_ads/transform.js (1)
trackResponseBuilder(132-161)
src/v0/destinations/tiktok_ads/transformV2.js (2)
src/v0/destinations/tiktok_ads/util.js (2)
message(11-11)getEventSource(78-111)src/v0/util/index.js (7)
get(14-14)message(1162-1162)message(1196-1196)getSuccessRespEvents(499-511)metadata(959-971)metadata(1986-1986)sortBatchesByMinJobId(2274-2279)
src/v0/destinations/tiktok_ads/util.test.js (1)
src/v0/destinations/tiktok_ads/util.js (2)
hashUserField(37-70)getEventSource(78-111)
⏰ 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 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 (go)
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (11)
src/v0/destinations/tiktok_ads/util.test.js (3)
175-185: LGTM! Comprehensive testing for device ID hashing.The test correctly verifies that both
idfaandgaidfields are hashed when present, ensuring data privacy for mobile device identifiers.
187-196: LGTM! Good coverage for array phone number hashing.The test properly validates the array handling logic for phone numbers, which aligns with the existing external_id array test pattern.
199-243: Well-structured test suite forgetEventSourceutility.The test suite provides excellent coverage of the event source resolution logic, including:
- Priority order validation (eventSource > event_source > channel)
- Fallback to "web" for invalid/missing values
- Backward compatibility mappings (mobile → app)
- Snake_case support
src/v0/destinations/tiktok_ads/transformV2.test.js (4)
144-166: Excellent test for content enrichment feature.The test effectively validates the new
contents_idsandnum_itemsfields are correctly populated from product data.
168-188: Good OS-specific privacy handling test for iOS.The test correctly verifies that
gaidis removed for Apple devices whileidfaremains defined.
190-211: Proper Android privacy test coverage.The test validates that
idfaandidfvare removed for Android whilegaidremains defined.
213-231: Good validation of snake_case event_source support.The test confirms that
event_sourcein snake_case format is properly recognized and used.src/v0/destinations/tiktok_ads/transformV2.js (4)
64-74: LGTM! Content enrichment implementation is correct.The implementation properly extracts
content_idvalues and only addscontents_idsandnum_itemswhen valid IDs are present, addressing the previous review comment about aligning these fields.
85-95: Well-implemented OS-based privacy filtering.The code correctly removes device identifiers based on the operating system to comply with platform-specific privacy requirements.
166-166: Good integration of dynamic event source resolution.Using
getEventSource(message)instead of a hardcoded value provides proper flexibility for event source determination.
797-805: Excellent implementation of event source-based batching!The implementation properly groups events by
event_sourcebefore batching, which aligns with the acknowledged future enhancement plan from the previous review. This ensures all events in a batch have the same event source value.
… batching logic with grouping (#4501) * feat: enable group by event_source before batching * feat: add missing parameter for app event_source * chore: refactor test cases * chore: revert unwanted changes to test cases --------- Co-authored-by: Sudip Paul <[email protected]>
* feat: add missing parameters and refactor code * chore: fix as per cursor review * chore: add test cases to increase coverage * feat: add support of mapping to consider default eventSource --------- Co-authored-by: Sudip Paul <[email protected]>
a5e4405 to
3645d8c
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
src/v0/destinations/tiktok_ads/util.js (2)
61-67: Normalize and consistently hash mobile IDs (IDFA/GAID).Lowercasing the hex after hashing IDFA while not doing the same for GAID is inconsistent and not equivalent to normalizing inputs pre-hash. To avoid discrepancies across clients and align with common partner requirements, normalize inputs before hashing (strip hyphens and lowercase), and keep output casing consistent.
Apply this diff:
- if (idfa) { - updatedUser.idfa = hashString(idfa).toString().toLowerCase(); - } - - if (gaid) { - updatedUser.gaid = hashString(gaid).toString(); - } + if (idfa) { + const normalizedIdfa = idfa.toString().replace(/-/g, '').toLowerCase(); + updatedUser.idfa = hashString(normalizedIdfa).toString(); + } + + if (gaid) { + const normalizedGaid = gaid.toString().replace(/-/g, '').toLowerCase(); + updatedUser.gaid = hashString(normalizedGaid).toString(); + }
78-111: Make event source resolution case-insensitive and whitespace-tolerant.Inputs like " Mobile " or "APP" should resolve correctly. Normalizing strings reduces edge cases and support burden.
Apply this diff:
const getEventSource = ({ properties, channel }) => { const supportedSources = ['web', 'app', 'offline', 'crm']; // Mapping for backward compatibility and new mappings const sourceMapping = { web: 'web', mobile: 'app', server: 'offline', sources: 'offline', }; const { eventSource, event_source: eventSourceV2 } = properties || {}; // Helper function to resolve source with mapping - const resolveSource = (source) => { - if (!source) return null; - - // First check if it's a direct supported source - if (supportedSources.includes(source)) { - return source; - } - - // Then check if it needs mapping - if (sourceMapping[source]) { - return sourceMapping[source]; - } - - return null; - }; + const normalize = (val) => (typeof val === 'string' ? val.trim().toLowerCase() : val); + const resolveSource = (source) => { + const s = normalize(source); + if (!s) return null; + if (supportedSources.includes(s)) { + return s; + } + if (sourceMapping[s]) { + return sourceMapping[s]; + } + return null; + }; return ( resolveSource(eventSource) || resolveSource(eventSourceV2) || resolveSource(channel) || 'web' ); };src/v0/destinations/tiktok_ads/util.test.js (2)
175-197: Expand assertions to validate normalization behavior (if adopted).Current tests ensure idfa/gaid are hashed. If we normalize inputs pre-hash (strip hyphens + lowercase), add assertions to lock in that behavior and prevent regressions.
Example additions:
it('normalizes IDFA/GAID before hashing (strip hyphens, lowercase)', () => { const user = { idfa: 'AEBE52E7-03EE-455A-B3C4-E57283966239', gaid: '38400000-8CF0-11BD-B23E-10B96E40000D', }; const hashedUser = hashUserField(user); // compute expected hashes inline if you have a local hasher util exposed to tests, // otherwise at least assert lowercase hex format: expect(/^[a-f0-9]{64}$/.test(hashedUser.idfa)).toBe(true); expect(/^[a-f0-9]{64}$/.test(hashedUser.gaid)).toBe(true); });
199-244: Add test cases for mappings and input normalization in getEventSource.You’ve covered core paths. Consider adding:
- Mapping checks: 'server' and 'sources' → 'offline'
- Channel mapping for 'mobile' → 'app'
- Case/whitespace normalization: ' APP ', 'Mobile', ' CRM ' resolve as expected
Proposed additions:
it('maps eventSource="server" to "offline"', () => { expect(getEventSource({ properties: { eventSource: 'server' } })).toBe('offline'); }); it('maps channel="sources" to "offline" when properties are absent', () => { expect(getEventSource({ properties: {}, channel: 'sources' })).toBe('offline'); }); it('maps channel="mobile" to "app" when eventSource missing', () => { expect(getEventSource({ properties: {}, channel: 'mobile' })).toBe('app'); }); // If input normalization is adopted: it('is case-insensitive and trims whitespace', () => { expect(getEventSource({ properties: { eventSource: ' APP ' }, channel: 'WEB' })).toBe('app'); expect(getEventSource({ properties: {}, channel: ' CRM ' })).toBe('crm'); });
📜 Review details
Configuration used: .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 a5e4405728c6701e315961879d776297b1325d2d and 3645d8c.
⛔ Files ignored due to path filters (3)
src/v0/destinations/tiktok_ads/data/TikTokTrackV2.jsonis excluded by!**/*.jsontest/integrations/destinations/tiktok_ads/processor/data.tsis excluded by!**/test/**test/integrations/destinations/tiktok_ads/router/data.tsis excluded by!**/test/**
📒 Files selected for processing (4)
src/v0/destinations/tiktok_ads/transformV2.js(11 hunks)src/v0/destinations/tiktok_ads/transformV2.test.js(1 hunks)src/v0/destinations/tiktok_ads/util.js(2 hunks)src/v0/destinations/tiktok_ads/util.test.js(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/v0/destinations/tiktok_ads/transformV2.test.js
- src/v0/destinations/tiktok_ads/transformV2.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/tiktok_ads/util.jssrc/v0/destinations/tiktok_ads/util.test.js
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
📚 Learning: 2025-07-15T06:27:07.528Z
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
Applied to files:
src/v0/destinations/tiktok_ads/util.jssrc/v0/destinations/tiktok_ads/util.test.js
🧬 Code Graph Analysis (2)
src/v0/destinations/tiktok_ads/util.js (3)
src/v0/destinations/tiktok_ads/transformV2.js (1)
externalId(77-77)src/v0/util/index.js (1)
externalId(1527-1527)src/v0/destinations/tiktok_ads/transform.js (1)
externalId(76-76)
src/v0/destinations/tiktok_ads/util.test.js (2)
src/v0/destinations/tiktok_ads/util.js (4)
require(1-1)hashUserField(37-70)message(11-11)getEventSource(78-111)src/v0/destinations/tiktok_ads/transformV2.js (5)
require(4-10)require(11-11)require(12-26)require(27-27)require(37-37)
⏰ 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 AMD64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Code Coverage
- GitHub Check: UT Tests
- GitHub Check: test_and_publish
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Analyze (go)
🔇 Additional comments (3)
src/v0/destinations/tiktok_ads/util.js (2)
40-40: Good addition: IDFA/GAID included in hashing scope.Including idfa and gaid in the destructuring is aligned with the PR goal to hash mobile identifiers. No issues here.
113-113: Export update looks correct.Exporting getEventSource alongside existing utilities is consistent with its usage in transformV2. No concerns.
src/v0/destinations/tiktok_ads/util.test.js (1)
1-1: Import update is correct.Tests now cover getEventSource from util.js as expected.
|
Allure Test reports for this run are available at:
|
|



What are the changes introduced in this PR?
This PR enhances the TikTok Ads V2 destination integration by implementing dynamic event source mapping instead of using static values. The changes focus on improving data accuracy, enhancing batching logic, and providing comprehensive test coverage.
Core Changes
Dynamic Event Source Resolution:
getEventSourceutility insrc/v0/destinations/tiktok_ads/util.jsto dynamically resolve event sources from message propertieseventSource,event_source, andchannel['web', 'app', 'offline', 'crm']mobile→app,server/sources→offline)Enhanced Batching Logic:
processRouterDestfunction usinggroupByInBatchesevent_sourcebefore batching, improving processing efficiencyforEachInBatchesfor better event processing and source-based groupingMobile Advertising ID Support:
hashUserFieldfunction to properly handleidfaandgaidfieldsNew Field Mappings:
TikTokTrackV2.json:app.app_id,app.app_name,app.app_versionad.callback,ad.campaign_id,ad.ad_id,ad.creative_idad.is_retargeting,ad.attributed,ad.attribution_type,ad.attribution_providerComprehensive Test Coverage:
getEventSourcefunction covering all scenarioscontents_ids,num_items, andeventSource: 'app'propertieschannel: 'web'tochannel: 'app'in relevant test casesWhat is the related Linear task?
https://linear.app/rudderstack/issue/INT-3933/investigate-hardcoded-event-source-in-tiktok-ads-v2-integration
Please explain the objectives of your changes below
Any changes to existing capabilities/behaviour, mention the reason & what are the changes?
Previous Behavior: The event source was always set to the static value
'web', regardless of the actual source of the event. This limited flexibility and did not accurately represent the true event source.New Behavior:
web,app,offline,crm)Reason for Change: The static approach limited data granularity and could impact downstream analytics. The dynamic approach provides more accurate event attribution and better aligns with TikTok's requirements.
Any new dependencies introduced with this change?
No new external dependencies were introduced. The changes utilize existing utility functions from
@rudderstack/integrations-libsuch asgroupByInBatchesandforEachInBatches.Any new generic utility introduced or modified. Please explain the changes.
Modified Utilities:
getEventSourcefunction: Enhanced with comprehensive source resolution logic, validation, and backward compatibility mappinghashUserFieldfunction: Improved to handle mobile advertising IDs with OS-specific filteringprocessRouterDestfunction: Enhanced with event source-based grouping for better batchingAny technical or performance related pointers to consider with the change?
Performance Improvements:
groupByInBatchesTechnical Considerations:
Success Criteria
web,app,offline,crm) are returnedDeveloper checklist
Reviewer checklist