Repository navigation
feat(custom_audience): router transform pipeline - #5187
Conversation
|
Note
|
| Layer / File(s) | Summary |
|---|---|
Batching Framework Generic Types and Connection Support src/services/destination/nativeBatching/batchDestination.ts, src/services/destination/nativeBatching/processBatchedDestination.ts, src/services/destination/nativeBatching/types.ts |
BatchDestinationConstructor now accepts (destination, connection?) and both are generically typed; BatchDestination stores both protected fields. processBatchedDestination extracts optional connection from events and passes it to the integration constructor. TransformedEvent gains optional internalGroupKey field for additional batching grouping dimensions. |
Custom Audience Types, Constants, and Configuration Schema src/v0/destinations/custom_audience/types.ts, src/v0/destinations/custom_audience/constants.ts |
Complete type hierarchy defined: Action, AuthenticationType, HttpMethod, ActionFieldConfig, ActionConfig, CustomAudienceDestConfig, CustomAudienceConnectionDestConfig, and CustomAudienceRouterRequest. Constants enumerate supported HTTP methods, authentication types (NO_AUTH, BASIC_AUTH, BEARER_TOKEN, API_KEY), and error message templates. |
Custom Audience Helper Utilities src/v0/destinations/custom_audience/utils.ts, src/v0/destinations/custom_audience/utils.test.ts |
Six utility functions: lookupActionConfig (fetch action config), evaluateTemplate (JSONata evaluation), resolveEndpoint (interpolate endpoint template with base URL), injectCustomMappings (apply field mappings), processFields (build audience record with optional hashing), and buildRequestHeaders (construct headers with authentication). Comprehensive tests cover success and error paths for all utilities. |
Custom Audience Router Transform and Batch Strategy src/v0/destinations/custom_audience/routerTransform.ts, src/v0/destinations/custom_audience/routerTransform.test.ts |
CustomAudienceIntegration extends BatchDestination: validates input schema via Zod, transforms events by selecting action config and processing fields, caches resolved endpoints per action, and implements getBatchStrategy() to group payloads by action then chunk by per-action batch size. Tests verify grouping/batching, error handling (missing action, stripped fields, schema failures), field hashing, authentication header injection, and template rendering failures. |
Feature Enablement src/constants/batchedDestinationsMap.ts, src/features.ts |
Registers CUSTOM_AUDIENCE: true in the batching destinations map (GA-enabled) and adds it to defaultFeaturesConfig.routerTransform. |
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
- rudderlabs/rudder-transformer#5093: Introduced the batching framework gating mechanism that this PR builds upon; Custom Audience now uses the same batching-framework path.
Suggested reviewers
- krishna2020
- maheshkutty
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title clearly summarizes the main change: adding a router transform pipeline for the Custom Audience destination feature. |
| Description check | ✅ Passed | The PR description comprehensively covers all required sections: changes overview, objectives, framework extensions, design decisions, test plan, and dependencies—far exceeding template minimums. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
📝 Generate docstrings
- Create stacked PR
- Commit on current branch
🧪 Generate unit tests (beta)
- Create PR with unit tests
- Commit unit tests in branch
feat/int-6299-router-transform-core-pipeline
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.
Comment @coderabbitai help to get the list of available commands and usage tips.
fbfdb58 to
5f61819
Compare
9ecb2fb to
f18347f
Compare
7a527f7 to
8b5ada2
Compare
…ouping and template-driven request bodies
8b5ada2 to
a1eb3ca
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #5187 +/- ##
===========================================
+ Coverage 92.30% 92.32% +0.01%
===========================================
Files 675 678 +3
Lines 37020 37133 +113
Branches 8645 8689 +44
===========================================
+ Hits 34172 34282 +110
+ Misses 2631 2613 -18
- Partials 217 238 +21 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
- Rename CustomAudienceConnectionConfig to CustomAudienceConnectionDestConfig for clarity - Extract endpoint resolution from constructor into buildEndpointsByAction() - Add connection guard in constructor with InstrumentationError Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/services/destination/nativeBatching/processBatchedDestination.ts`:
- Around line 209-213: The current selection of connection via events.find(...)
is order-dependent and can misapply a connection across mixed inputs; change
connection resolution to use the first event's connection (events[0].connection)
as the deterministic source and then validate that every event in events has the
same connection (compare by a stable identifier or deep equality) and reject or
throw (return an error) if any event has a different connection; then pass that
validated connection into the IntegrationClass constructor (where
IntegrationClass(destination as Destination<TConfig>, connection) is created) so
the batch only proceeds when all events share the same connection.
In `@src/v0/destinations/custom_audience/routerTransform.test.ts`:
- Around line 45-49: Tests reuse mutable fixtures baseInsertAction and
baseDeleteAction when calling buildDestination(), and a test mutates
insert.requestBody which makes test order-dependent; fix by passing deep-cloned
action objects (or fresh action factories) into buildDestination() instead of
the shared baseInsertAction/baseDeleteAction so each test gets its own copy
(e.g., clone the action before using it in buildDestination() or replace base*
fixtures with functions that return new objects), ensuring insert.requestBody
mutations do not affect other tests.
In `@src/v0/destinations/custom_audience/routerTransform.ts`:
- Around line 55-63: Precompute endpoints must guard against undefined action
configs: in routerTransform.ts where you iterate
Object.entries(this.destination.Config.actions) and call
resolveEndpoint(actionConfig!.endpoint, ...), replace the non-null assertion
with a runtime check for actionConfig and if it's undefined throw or surface a
consistent instrumentation error (including the action key and context) instead
of allowing a generic runtime exception; ensure you reference the same symbols
(this.destination.Config.actions, actionConfig, resolveEndpoint) so the map
either returns a valid resolved endpoint or fails with the instrumentation error
for missing action configs.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1098d8f4-14e4-48ea-a392-f6ddb64bef8d
⛔ Files ignored due to path filters (5)
.claude/skills/code-structure/SKILL.mdis excluded by!**/*.md.claude/skills/writing-tests/SKILL.mdis excluded by!**/*.mdtest/integrations/destinations/custom_audience/common.tsis excluded by!**/test/**test/integrations/destinations/custom_audience/maskedSecrets.tsis excluded by!**/test/**test/integrations/destinations/custom_audience/router/data.tsis excluded by!**/test/**
📒 Files selected for processing (11)
src/constants/batchedDestinationsMap.tssrc/features.tssrc/services/destination/nativeBatching/batchDestination.tssrc/services/destination/nativeBatching/processBatchedDestination.tssrc/services/destination/nativeBatching/types.tssrc/v0/destinations/custom_audience/constants.tssrc/v0/destinations/custom_audience/routerTransform.test.tssrc/v0/destinations/custom_audience/routerTransform.tssrc/v0/destinations/custom_audience/types.tssrc/v0/destinations/custom_audience/utils.test.tssrc/v0/destinations/custom_audience/utils.ts
|



Summary
Adds router transform support for the Custom Audience destination, built on the native batching framework.
Custom Audience integration
Each incoming record event goes through: action lookup → custom-mapping injection → field processing (empty-stripping + optional SHA256/SHA512/MD5 hashing via
processAudienceRecord). The result is a typedTransformedEventcarrying the cleaned record.Key design choices:
internalGroupKeyfield keeps insert/update/delete in separate batches even when their (endpoint, method, headers) happen to match. Each action carries its ownrequestBodytemplate, so mixing them would produce wrong payloads.ChunkBatchStrategywithmaxItems: actionConfig.batchSizeand awrapBodythat evaluates the action'srequestBodyjson-template against the batched records and connection config.customMappingsinject literal values onto each record before template evaluation. Thefrom/tonaming follows the upstream schema convention (documented with JSDoc since semantics are inverted from the usual source→target pattern).Framework extensions
BatchDestination,BatchDestinationConstructor, andprocessBatchedDestination— addedTConfig/TConnectionConfigtype parameters so subclasses get typedDestination.ConfigandConnection<T>. Defaults toRecord<string, unknown>to preserve backward compatibility (PostHog compiles unchanged).connectionis extracted from the first event and passed into the constructor by the framework. All events in a single router-transform call share the same connection (rudder-server groups by source+destination), so this is safe.internalGroupKeyonTransformedEvent— an optional discriminator included in the composite grouping key. Lets destinations add grouping dimensions beyond the user-visible request fields without polluting headers or params.Wiring
CUSTOM_AUDIENCE: truetobatchedDestinationsMapandfeatures.routerTransformso the dispatcher routes throughprocessBatchedDestination.JsonTemplateEngine.createAsSyncin-process —TODO(INT-6295)marks the swap point for sandboxed evaluation.Known behavior: single-element JSONata array flattening
When a
requestBodytemplate maps over$.recordsand there is exactly one record, the json-template-engine returns a plain object instead of a single-element array (standard JSONata semantics). This is tested explicitly and template authors should account for it if the downstream API requires an array.Test plan
npm run lint— cleannpm test -- --testPathPattern="custom_audience" --no-coverage— 29 unit tests pass (21 utils + 8 routerTransform, both table-driven; includes explicit single-element JSONata flattening assertion)npm test -- --testPathPattern="batchedDestinationsMap|nativeBatching|posthog" --no-coverage— framework + PostHog regression tests pass with no changesnpm run test:ts -- component --destination=custom_audience— 5 router scenarios pass: action grouping + chunking, missing-action 400, all-fields-stripped 400, customMappings literal injection, and isHashRequired SHA256 hashingnpm run test:ts -- component --destination=posthog— PostHog component tests pass (no framework regression)Dependencies
feat/int-6296-isolate-vm-integration-for-template-parsing). Merge order matters.actionsuppercase; this implementation expects lowercase per audience-destination convention.🤖 Generated with Claude Code