Skip to content

feat(custom_audience): router transform pipeline - #5187

Merged
shekhar-rudder merged 2 commits into
developfrom
feat/int-6299-router-transform-core-pipeline
May 15, 2026
Merged

shekhar-rudder merged 2 commits into
developfrom
feat/int-6299-router-transform-core-pipeline

Conversation

@shekhar-rudder

@shekhar-rudder shekhar-rudder commented May 6, 2026 •

Copy link
Copy Markdown
Member

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 typed TransformedEvent carrying the cleaned record.

Key design choices:

  • Eager endpoint resolution — endpoints and request headers are computed once per configured action in the constructor, not per event.
  • Action-aware grouping — a new internalGroupKey field keeps insert/update/delete in separate batches even when their (endpoint, method, headers) happen to match. Each action carries its own requestBody template, so mixing them would produce wrong payloads.
  • Per-action chunking — uses ChunkBatchStrategy with maxItems: actionConfig.batchSize and a wrapBody that evaluates the action's requestBody json-template against the batched records and connection config.
  • Authentication — supports noAuth, Basic, Bearer token, and API key header styles, resolved from destination config.
  • Custom mappings — connection-level customMappings inject literal values onto each record before template evaluation. The from/to naming follows the upstream schema convention (documented with JSDoc since semantics are inverted from the usual source→target pattern).

Framework extensions

  • Typed generics on BatchDestination, BatchDestinationConstructor, and processBatchedDestination — added TConfig / TConnectionConfig type parameters so subclasses get typed Destination.Config and Connection<T>. Defaults to Record<string, unknown> to preserve backward compatibility (PostHog compiles unchanged).
  • Connection injection — connection is 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.
  • internalGroupKey on TransformedEvent — 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

  • Added CUSTOM_AUDIENCE: true to batchedDestinationsMap and features.routerTransform so the dispatcher routes through processBatchedDestination.
  • Template execution uses JsonTemplateEngine.createAsSync in-process — TODO(INT-6295) marks the swap point for sandboxed evaluation.

Known behavior: single-element JSONata array flattening

When a requestBody template maps over $.records and 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 — clean
  • npm 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 changes
  • npm 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 hashing
  • npm run test:ts -- component --destination=posthog — PostHog component tests pass (no framework regression)

Dependencies

  • Stacked on top of PR feat(custom_audience): sandbox template parsing in isolated-vm #5185 (feat/int-6296-isolate-vm-integration-for-template-parsing). Merge order matters.
  • INT-6295 (Template Evaluator) for sandboxed execution — stubbed with a TODO
  • INT-6290 for the rudder-integrations-config destination definition. That schema currently keys actions uppercase; this implementation expects lowercase per audience-destination convention.

🤖 Generated with Claude Code

@shekhar-rudder
shekhar-rudder requested a review from a team as a code owner May 6, 2026 04:55
@shekhar-rudder
shekhar-rudder requested review from krishna2020 and maheshkutty and removed request for a team May 6, 2026 04:55
@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key(s) in object: 'auto_resolve_threads'
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Summary by CodeRabbit

New Features

  • Added Custom Audience destination with support for batching, field hashing, custom field mappings, and multiple authentication methods (Bearer token, API key, and Basic auth).

Walkthrough

This PR implements a complete Custom Audience destination using an extended batching framework. The changes generalize BatchDestination to support typed connections, define the Custom Audience configuration schema, provide utility functions for field processing and authentication, implement the integration class with action-based batching, and register the destination as GA-enabled.

Changes

Custom Audience Destination Implementation

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 ⚠️ Warning 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.

❤️ Share

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

@shekhar-rudder
shekhar-rudder force-pushed the feat/int-6296-isolate-vm-integration-for-template-parsing branch from fbfdb58 to 5f61819 Compare May 12, 2026 08:18
@shekhar-rudder
shekhar-rudder requested review from a team as code owners May 12, 2026 08:18
@shekhar-rudder
shekhar-rudder force-pushed the feat/int-6296-isolate-vm-integration-for-template-parsing branch 3 times, most recently from 9ecb2fb to f18347f Compare May 12, 2026 10:15
Base automatically changed from feat/int-6296-isolate-vm-integration-for-template-parsing to develop May 14, 2026 12:09
@shekhar-rudder
shekhar-rudder force-pushed the feat/int-6299-router-transform-core-pipeline branch from 7a527f7 to 8b5ada2 Compare May 14, 2026 12:15
@shekhar-rudder
shekhar-rudder force-pushed the feat/int-6299-router-transform-core-pipeline branch from 8b5ada2 to a1eb3ca Compare May 14, 2026 12:23
@codecov

codecov Bot commented May 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.43590% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.32%. Comparing base (fc600d3) to head (bbb25e7).

Files with missing lines Patch % Lines
src/v0/destinations/custom_audience/utils.ts 97.22% 2 Missing ⚠️
...v0/destinations/custom_audience/routerTransform.ts 96.96% 1 Missing ⚠️
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.
📢 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.

- 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]>

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between fc600d3 and bbb25e7.

⛔ Files ignored due to path filters (5)
  • .claude/skills/code-structure/SKILL.md is excluded by !**/*.md
  • .claude/skills/writing-tests/SKILL.md is excluded by !**/*.md
  • test/integrations/destinations/custom_audience/common.ts is excluded by !**/test/**
  • test/integrations/destinations/custom_audience/maskedSecrets.ts is excluded by !**/test/**
  • test/integrations/destinations/custom_audience/router/data.ts is excluded by !**/test/**
📒 Files selected for processing (11)
  • src/constants/batchedDestinationsMap.ts
  • src/features.ts
  • src/services/destination/nativeBatching/batchDestination.ts
  • src/services/destination/nativeBatching/processBatchedDestination.ts
  • src/services/destination/nativeBatching/types.ts
  • src/v0/destinations/custom_audience/constants.ts
  • src/v0/destinations/custom_audience/routerTransform.test.ts
  • src/v0/destinations/custom_audience/routerTransform.ts
  • src/v0/destinations/custom_audience/types.ts
  • src/v0/destinations/custom_audience/utils.test.ts
  • src/v0/destinations/custom_audience/utils.ts

@sonarqubecloud

Copy link
Copy Markdown

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.

2 participants