Repository navigation
refactor: onboard batching framework - #5093
Conversation
🔒 Scanned for secrets using gitleaks 8.28.0
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Note
|
| Cohort / File(s) | Summary |
|---|---|
Batching Feature Flag src/constants/batchedDestinationsMap.ts |
New exported batchedDestinationsMap and isBatchingFrameworkEnabled(destType, workspaceId?) implementing CSV env parsing, ALL sentinel, caching, and case-insensitive dest lookup. |
Fetch Handler & Dynamic Loader src/helpers/fetchHandlers.ts, src/services/misc.ts |
Added FetchHandler.routerTransformHandlerMap and getRouterTransformHandler(dest) with lowercase caching; MiscService.getRouterTransformHandler(dest) dynamically requires .../routerTransform and returns Integration constructor typed as BatchDestinationConstructor. |
Router Integration Primitives src/services/destination/routerIntegration.ts |
New module: types (TransformedEvent, TransformResult, TransformError), batch strategy types and factories (chunk, customBatch), helpers (parseSizeToBytes, grouping, metadata resolution), and abstract BatchDestination<TBody> with transformEvents, validate, and error-generation utilities. |
Batching Orchestration src/services/destination/processBatchedDestination.ts |
New exported processBatchedDestination(...) implementing validation, partitioning by dontBatch, invoking transformEvents for batchable/non-batchable, applying chunk/custom strategies, converting to server-format responses, multiplex cleanup, and combining results. |
Native Integration Hook src/services/destination/nativeIntegration.ts |
Modified doRouterTransformation to call isBatchingFrameworkEnabled; when enabled uses router-transform integration via FetchHandler.getRouterTransformHandler() and delegates to processBatchedDestination(), otherwise retains existing getDestHandler path. |
Tests — Feature Flag src/services/destination/__tests__/batchingFrameworkFeatureFlag.test.ts |
New tests for isBatchingFrameworkEnabled() covering env parsing, trimming, ALL, unset/empty handling, and case-insensitive destination matching. |
Tests — Router Integration src/services/destination/__tests__/routerIntegration.test.ts |
New tests for parseSizeToBytes, grouping helpers, metadata resolution, BatchDestination behaviors (transform, validate, error mapping), and batch-strategy factories. |
Tests — Batching Pipeline src/services/destination/__tests__/processBatchedDestination.test.ts |
Comprehensive tests exercising chunk batching, endpoint grouping, custom merge batching, dont-batch passthrough, transform/schema failures, instrumentation errors, and multiplex metadata handling. |
Sequence Diagram(s)
sequenceDiagram
actor Client
participant NativeIntegration as NativeIntegration
participant Gating as isBatchingFrameworkEnabled
participant FetchHandler
participant MiscService
participant ProcessBatched as processBatchedDestination
participant RouterIntegration as RouterIntegration Instance
participant PostTransform as DestinationPostTransformationService
Client->>NativeIntegration: doRouterTransformation(events, destType, version)
NativeIntegration->>Gating: isBatchingFrameworkEnabled(destType, workspaceId)
alt Batching Enabled
Gating-->>NativeIntegration: true
NativeIntegration->>FetchHandler: getRouterTransformHandler(destType)
FetchHandler->>MiscService: (dynamic import if uncached)
MiscService-->>FetchHandler: RouterIntegrationConstructor
FetchHandler-->>NativeIntegration: RouterIntegrationConstructor
NativeIntegration->>ProcessBatched: processBatchedDestination(events, Constructor, reqMetadata)
ProcessBatched->>RouterIntegration: new Integration(destination)
ProcessBatched->>RouterIntegration: validate(inputs)
RouterIntegration-->>ProcessBatched: validatedInputs / errorEvents
ProcessBatched->>RouterIntegration: transformEvents(batchableInputs)
RouterIntegration-->>ProcessBatched: {payloads, errorEvents}
ProcessBatched->>RouterIntegration: transformEvents(nonBatchableInputs) (per-item)
RouterIntegration-->>ProcessBatched: {payloads, errorEvents}
ProcessBatched->>ProcessBatched: groupPayloadsByCompositeKey -> apply strategies -> build batched responses
ProcessBatched-->>NativeIntegration: RouterTransformationResponse[]
else Batching Disabled
Gating-->>NativeIntegration: false
NativeIntegration->>FetchHandler: getDestHandler(destType, version)
NativeIntegration->>NativeIntegration: processRouterDest(...) (existing non-batched flow)
NativeIntegration-->>NativeIntegration: transformedResponse
end
NativeIntegration->>PostTransform: handleRouterTransformSuccessEvents(transformedResponse)
PostTransform-->>Client: processed results
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | Docstring coverage is 38.46% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (2 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title 'refactor: onboard batching framework' accurately summarizes the main change—introducing a new batching framework for router transformations—and is clear and specific. |
| Description check | ✅ Passed | The pull request provides a comprehensive description covering objectives, architecture, feature flags, and technical considerations aligned with the template structure. |
✏️ 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
INT-6025/feat/addBatchingFramework
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.
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/services/destination/nativeIntegration.ts`:
- Around line 107-115: The current logic computes useBatchingFramework once
using workspaceId from events[0], which wrongly applies that decision to every
destInputArray; update the code so the batching flag and handler selection are
evaluated inside the per-group callback (where destInputArray is available) by
reading workspaceId = destInputArray[0].metadata?.workspaceId, then call
isBatchingFrameworkEnabled(destinationType, workspaceId) there and pick either
FetchHandler.getDestHandler(destinationType, version) or
FetchHandler.getRouterTransformHandler(destinationType) per group; also guard
against missing metadata (validate destInputArray[0] before using workspaceId)
and add a test that sends a routerTransform request with mixed workspaces to
prevent regression.
In `@src/services/destination/processBatchedDestination.ts`:
- Around line 122-130: The exported function processBatchedDestination currently
reads events[0] and will throw on an empty array; add an early guard at the top
of processBatchedDestination that returns an empty
RouterTransformationResponse[] (no-op) when events.length === 0 to avoid
accessing events[0], and update the new empty-input unit test to call
processBatchedDestination([]) to assert the no-op return; reference the
events[0] usage and the processBatchedDestination function when making the
change.
- Around line 24-65: The function applyChunkStrategy undercounts request size
because it measures only payload.body; change the sizing logic to build the
candidate wrapped body before deciding to append: compute prospectiveBody =
strategy.wrapBody([...currentBodies, payload.body]) and use
Buffer.byteLength(JSON.stringify(prospectiveBody)) (or a provided size callback)
to compare against maxBytes; if the prospective size would exceed maxBytes,
flush the current batch first (unless currentBodies is empty, in which case emit
the single wrapped candidate as its own batch), then continue; update references
to currentBodies, currentBytes and the flush logic accordingly so decisions are
based on the final wrapped request size.
In `@src/services/destination/routerIntegration.ts`:
- Around line 216-217: Remove the debug console log that prints request-scoped
data: delete the line `console.log(_reqMetadata)` in the `batchTransform()` path
(or replace it with a secure, low-volume logger call at trace/debug level that
redacts sensitive fields if you must keep it). Ensure no other direct stdout
logging of `_reqMetadata` remains and remove the "// TODO: remove this" comment
so the noisy, potentially sensitive debug output is not executed in production.
- Around line 221-237: When catching transformEvent() errors inside the inputs
loop, ensure that if the input has metadata?.dontBatch === true the default
statusCode is set to 400 (unless the thrown error already sets statusCode);
update the errorEvents.push block that currently uses error.statusCode || 500 to
instead use error.statusCode ?? (input.metadata?.dontBatch ? 400 : 500), and
preserve the existing error.message, jobId, and statTags fields so poison
messages that were singled out do not keep retrying.
- Around line 124-130: resolveMetadatas silently drops missing entries which
hides cases where a CustomBatchResult references an unknown jobId; change
resolveMetadatas (function resolveMetadatas, parameters jobIds and metadataMap)
to validate each id: iterate jobIds, look up metadataMap.get(id), and if the
lookup returns undefined throw an error (e.g., include the missing jobId and
context) instead of using filter(Boolean) so the function fails fast when a
jobId is unknown; return the array of metadatas only after all ids are
validated.
🪄 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: 62e3e1e1-fe4b-4db7-b267-7b26c0ef8339
⛔ Files ignored due to path filters (1)
test/integrations/destinations/posthog/router/batchingFramework.test.tsis excluded by!**/test/**
📒 Files selected for processing (9)
src/constants/batchedDestinationsMap.tssrc/helpers/fetchHandlers.tssrc/services/destination/__tests__/batchingFrameworkFeatureFlag.test.tssrc/services/destination/__tests__/processBatchedDestination.test.tssrc/services/destination/__tests__/routerIntegration.test.tssrc/services/destination/nativeIntegration.tssrc/services/destination/processBatchedDestination.tssrc/services/destination/routerIntegration.tssrc/services/misc.ts
🔒 Scanned for secrets using gitleaks 8.28.0
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #5093 +/- ##
===========================================
- Coverage 92.24% 92.23% -0.01%
===========================================
Files 659 669 +10
Lines 36120 36472 +352
Branches 8497 8534 +37
===========================================
+ Hits 33318 33641 +323
- Misses 2563 2614 +51
+ Partials 239 217 -22 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/services/destination/routerIntegration.ts (1)
224-240:⚠️ Potential issue | 🟠 MajorDefault second-pass
dontBatchfailures to 400.Lines 235-237 still return 500 when
transformEvent()throws without its own status code, even if the event is already on the isolated retry path (metadata.dontBatch === true). That keeps poison messages retryable unless every integration remembers to override it.🛠️ Suggested fix
} catch (error: any) { + const defaultStatusCode = input.metadata?.dontBatch === true ? 400 : 500; errorEvents.push({ error: error.message || 'Unknown error during transformation', - statusCode: error.statusCode || 500, + statusCode: error.statusCode ?? defaultStatusCode, jobId, statTags: error.statTags, }); }Based on learnings, in
src/v1/destinations/am/networkHandler.tsthe retry flow intentionally uses 500 for the first failure and 400 aftermetadata.dontBatch=trueto prevent infinite retries.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/services/destination/routerIntegration.ts` around lines 224 - 240, The transformEvent error handler currently defaults statusCode to 500 which causes second-pass (metadata.dontBatch === true) failures to remain retryable; update the catch block in the inputs loop (where transformEvent is called and errorEvents are pushed) to default statusCode to 400 when input.metadata?.dontBatch is true (otherwise keep existing error.statusCode || 500), and include the jobId/statTags as before so the isolated retry path produces a non-retryable 400 for poison messages.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/services/destination/processBatchedDestination.ts`:
- Around line 165-187: The nonBatchable loop currently only handles
strategy.type === 'chunk' and therefore ignores destinations using
customBatch/custom strategies; update the loop inside processBatchedDestination
so it obtains the batch strategy via
integration.getBatchStrategy(payload.endpoint) and, for each payload, if the
strategy exposes a wrapBody function (or strategy.type indicates 'chunk' or
'custom'), call strategy.wrapBody([payload.body]) to let the destination
shape/aggregate the array of bodies; otherwise shallow-copy the payload.body as
before. Keep the existing per-payload jobIds Set and call convertToServerFormat
with the wrappedBody so customBatch logic is honored while preserving cross-job
isolation.
---
Duplicate comments:
In `@src/services/destination/routerIntegration.ts`:
- Around line 224-240: The transformEvent error handler currently defaults
statusCode to 500 which causes second-pass (metadata.dontBatch === true)
failures to remain retryable; update the catch block in the inputs loop (where
transformEvent is called and errorEvents are pushed) to default statusCode to
400 when input.metadata?.dontBatch is true (otherwise keep existing
error.statusCode || 500), and include the jobId/statTags as before so the
isolated retry path produces a non-retryable 400 for poison messages.
🪄 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: 8b6c2b47-4396-4f6d-89ba-f0c200f71d26
📒 Files selected for processing (4)
src/services/destination/__tests__/routerIntegration.test.tssrc/services/destination/nativeIntegration.tssrc/services/destination/processBatchedDestination.tssrc/services/destination/routerIntegration.ts
✅ Files skipped from review due to trivial changes (1)
- src/services/destination/tests/routerIntegration.test.ts
shekhar-rudder
left a comment
There was a problem hiding this comment.
Design review focused on extensibility ahead of onboarding multiple destinations.
shekhar-rudder
left a comment
There was a problem hiding this comment.
Naming Review
Suggestions to improve naming clarity across the batching framework abstraction, focused on making the API more self-documenting for engineers onboarding new destinations.
🔒 Scanned for secrets using gitleaks 8.28.0
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/services/destination/routerIntegration.ts (1)
63-69: Consider validating that at least one ofmaxSizeormaxBytesis provided inchunk()factory.A
ChunkStrategywith neithermaxSizenormaxByteswould have no meaningful chunking constraint. If this is unintentional, adding runtime validation would prevent misconfiguration.Suggested improvement
export function chunk<TBody extends Record<string, unknown> = Record<string, unknown>>(opts: { maxSize?: number; maxBytes?: string; wrapBody: (bodies: TBody[]) => Record<string, unknown>; }): ChunkStrategy<TBody> { + if (opts.maxSize === undefined && opts.maxBytes === undefined) { + throw new Error('ChunkStrategy requires at least one of maxSize or maxBytes'); + } return { type: 'chunk', ...opts }; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/services/destination/routerIntegration.ts` around lines 63 - 69, The chunk factory currently returns a ChunkStrategy even if neither opts.maxSize nor opts.maxBytes is provided; add a runtime validation in the chunk<TBody>(...) function to check that at least one of opts.maxSize or opts.maxBytes is defined and throw a clear Error (or assert) if both are missing. Update the chunk implementation to perform this check before returning { type: 'chunk', ...opts } so misconfigured ChunkStrategy instances are rejected early; reference opts.maxSize, opts.maxBytes and the chunk function/ChunkStrategy type when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/services/destination/routerIntegration.ts`:
- Around line 63-69: The chunk factory currently returns a ChunkStrategy even if
neither opts.maxSize nor opts.maxBytes is provided; add a runtime validation in
the chunk<TBody>(...) function to check that at least one of opts.maxSize or
opts.maxBytes is defined and throw a clear Error (or assert) if both are
missing. Update the chunk implementation to perform this check before returning
{ type: 'chunk', ...opts } so misconfigured ChunkStrategy instances are rejected
early; reference opts.maxSize, opts.maxBytes and the chunk
function/ChunkStrategy type when making the change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ac645cb6-798b-45af-9f08-8aed3680e115
📒 Files selected for processing (1)
src/services/destination/routerIntegration.ts
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
src/services/destination/routerIntegration.ts (2)
225-242:⚠️ Potential issue | 🟠 MajorPreserve the 400-on-second-pass retry behavior.
When
transformEvent()throws for an input that already hasmetadata.dontBatch === true, Line 239 still falls back to the generic status fromgenerateErrorObject(). That makes singled-out poison messages retryable by default again.Suggested change
} catch (error: any) { const errObj = generateErrorObject(error); + const defaultStatusCode = input.metadata?.dontBatch === true ? 400 : 500; + const statusCode = + errObj.status === 500 && error?.statusCode == null ? defaultStatusCode : errObj.status; errorEvents.push({ error: errObj.message || 'Unknown error during transformation', - statusCode: errObj.status, + statusCode, jobId, statTags: errObj.statTags, }); }Based on learnings, in
src/v1/destinations/am/networkHandler.tsfailures aftermetadata.dontBatch=truereturn 400 while first-pass failures return 500 to prevent infinite retries.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/services/destination/routerIntegration.ts` around lines 225 - 242, transformEvent() failures for inputs marked with metadata.dontBatch === true are currently using the generic status from generateErrorObject(), which can make poison messages retryable; update the catch block in routerIntegration.ts so that when input.metadata?.dontBatch is true you override the statusCode to 400 (while keeping errObj.message, errObj.statTags and jobId) before pushing into errorEvents; reference transformEvent, generateErrorObject, and the metadata.dontBatch flag and ensure the errorEvents entry uses statusCode: 400 for dontBatch inputs to preserve the one-pass non-retry behavior.
39-44: 🛠️ Refactor suggestion | 🟠 MajorAllow batched bodies to be arrays too.
Line 43, Line 47, and Line 208 still force the framework through
Record<string, unknown>, even though Line 206 explicitly calls outJSON_ARRAY. That makes array-body APIs awkward to onboard and weakens the “generic” contract. A sharedRequestPayload = Record<string, unknown> | unknown[]type threaded through these APIs would keep the abstraction aligned.Also applies to: 46-49, 204-214
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/services/destination/routerIntegration.ts` around lines 39 - 44, The ChunkStrategy definition and related APIs constrain batched bodies to Record<string, unknown> only; introduce a shared type alias (e.g., RequestPayload = Record<string, unknown> | unknown[]) and update the generic bounds and signatures to use it: change ChunkStrategy<TBody extends RequestPayload = RequestPayload> and update wrapBody to accept TBody[] and return RequestPayload (or RequestPayload[] where appropriate), then propagate this union type to all usages referenced in routerIntegration.ts (notably the ChunkStrategy type, wrapBody calls, and any function signatures around lines ~204-214) so array payloads (JSON_ARRAY) are supported consistently. Ensure callers and type annotations are updated to compile with the new RequestPayload union without altering runtime behavior.src/services/destination/processBatchedDestination.ts (1)
168-190:⚠️ Potential issue | 🟠 MajorReuse the normal batching flow inside the
dontBatchloop.Line 174 emits one request per transformed payload. That skips
customBatchentirely and also preventschunkstrategies from regrouping multiple payloads produced by the same input into one request.dontBatchshould isolate jobs from each other, not bypass request shaping within the same job.Suggested change
for (const single of nonBatchable) { // eslint-disable-next-line no-await-in-loop const singleResult = await integration.transformEvents([single], reqMetadata); allErrors.push(...singleResult.errorEvents); - - for (const payload of singleResult.payloads) { - const strategy = integration.getBatchStrategy(payload.endpoint); - const wrappedBody = - strategy.type === 'chunk' ? strategy.wrapBody([payload.body]) : { ...payload.body }; - results.push( - convertToServerFormat( - { body: wrappedBody, jobIds: new Set([payload.jobId]) }, - payload.endpoint, - payload.method, - payload.headers, - payload.params, - metadataMap, - destination, - integration, - ), - ); - } + const singleGroups = groupPayloadsByCompositeKey(singleResult.payloads); + for (const group of singleGroups) { + const strategy = integration.getBatchStrategy(group.endpoint); + const batchResults = + strategy.type === 'chunk' + ? applyChunkStrategy(group.payloads, strategy) + : strategy.batch(group.payloads); + + for (const batchResult of batchResults) { + results.push( + convertToServerFormat( + batchResult, + group.endpoint, + group.method, + group.headers, + group.params, + metadataMap, + destination, + integration, + ), + ); + } + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/services/destination/processBatchedDestination.ts` around lines 168 - 190, The dontBatch (nonBatchable) loop currently converts each transformed payload into its own request, bypassing the shared batching logic (customBatch and chunk grouping); instead, after calling integration.transformEvents([single], reqMetadata) for each single input in the nonBatchable loop, collect its returned payloads and feed them into the same batching pipeline used for batchable events: determine strategy via integration.getBatchStrategy(payload.endpoint), accumulate payloads from the same job/endpoint/strategy, apply strategy.customBatch(where applicable) or strategy.wrapBody for chunk grouping before calling convertToServerFormat, ensuring payloads produced by the same input can still be grouped per strategy while keeping jobs isolated from other inputs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/services/destination/processBatchedDestination.ts`:
- Around line 193-264: The code currently builds batch requests before removing
jobIds that already failed, causing successful batchedRequest.body to still
include failed jobs; after calling convertErrorEventsToResponses (where
errorResults are produced via convertErrorEventsToResponses/allErrors) compute
the set of failedJobIds from those error responses and then filter out any
payloads whose metadata.jobId is in that set from both batchablePayloads and any
singleResult.payloads (the nonBatchable entries) before proceeding to the
grouping/batching steps (groupPayloadsByCompositeKey, applyChunkStrategy,
strategy.batch). Ensure you also handle the early-return path (when
batchablePayloads becomes empty after filtering) so it returns results with no
remaining references to failed jobIds. Finally leave downstream reconciliation
(combineBatchRequestsWithSameJobIds) unchanged.
---
Duplicate comments:
In `@src/services/destination/processBatchedDestination.ts`:
- Around line 168-190: The dontBatch (nonBatchable) loop currently converts each
transformed payload into its own request, bypassing the shared batching logic
(customBatch and chunk grouping); instead, after calling
integration.transformEvents([single], reqMetadata) for each single input in the
nonBatchable loop, collect its returned payloads and feed them into the same
batching pipeline used for batchable events: determine strategy via
integration.getBatchStrategy(payload.endpoint), accumulate payloads from the
same job/endpoint/strategy, apply strategy.customBatch(where applicable) or
strategy.wrapBody for chunk grouping before calling convertToServerFormat,
ensuring payloads produced by the same input can still be grouped per strategy
while keeping jobs isolated from other inputs.
In `@src/services/destination/routerIntegration.ts`:
- Around line 225-242: transformEvent() failures for inputs marked with
metadata.dontBatch === true are currently using the generic status from
generateErrorObject(), which can make poison messages retryable; update the
catch block in routerIntegration.ts so that when input.metadata?.dontBatch is
true you override the statusCode to 400 (while keeping errObj.message,
errObj.statTags and jobId) before pushing into errorEvents; reference
transformEvent, generateErrorObject, and the metadata.dontBatch flag and ensure
the errorEvents entry uses statusCode: 400 for dontBatch inputs to preserve the
one-pass non-retry behavior.
- Around line 39-44: The ChunkStrategy definition and related APIs constrain
batched bodies to Record<string, unknown> only; introduce a shared type alias
(e.g., RequestPayload = Record<string, unknown> | unknown[]) and update the
generic bounds and signatures to use it: change ChunkStrategy<TBody extends
RequestPayload = RequestPayload> and update wrapBody to accept TBody[] and
return RequestPayload (or RequestPayload[] where appropriate), then propagate
this union type to all usages referenced in routerIntegration.ts (notably the
ChunkStrategy type, wrapBody calls, and any function signatures around lines
~204-214) so array payloads (JSON_ARRAY) are supported consistently. Ensure
callers and type annotations are updated to compile with the new RequestPayload
union without altering runtime behavior.
🪄 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: 1e36ae19-c9ae-488c-94e9-7ec3834b147e
📒 Files selected for processing (7)
src/constants/batchedDestinationsMap.tssrc/helpers/fetchHandlers.tssrc/services/destination/__tests__/processBatchedDestination.test.tssrc/services/destination/__tests__/routerIntegration.test.tssrc/services/destination/processBatchedDestination.tssrc/services/destination/routerIntegration.tssrc/services/misc.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- src/services/misc.ts
- src/helpers/fetchHandlers.ts
- src/constants/batchedDestinationsMap.ts
- src/services/destination/tests/processBatchedDestination.test.ts
- src/services/destination/tests/routerIntegration.test.ts
🔒 Scanned for secrets using gitleaks 8.28.0
🔒 Scanned for secrets using gitleaks 8.28.0
🔒 Scanned for secrets using gitleaks 8.28.0
🔒 Scanned for secrets using gitleaks 8.28.0
🔒 Scanned for secrets using gitleaks 8.28.0
🔒 Scanned for secrets using gitleaks 8.28.0
|



What are the changes introduced in this PR?
Introduces a generic Native Batching Framework for the
/routerTransformroute that standardises validation, chunking, metadata resolution, and response formatting. Destinations can opt in incrementally via a registry map or per-destination environment variable. The new code path is gated behind a feature flag for incremental rollout.What is the related Linear task?
Resolves INT-6025
Please explain the objectives of your changes below
Currently 50+ destinations each implement their own
processRouterDestwith duplicated batching logic — chunking, size limits, metadata alignment, and error handling. This framework extracts that into a reusableBatchDestination<TBody>abstract class so destinations only implement:transformEvent()— per-event transformationgetBatchStrategy()— returns aChunkBatchStrategyorCustomBatchStrategyinstancegetInputSchema()— Zod schema for integration-specific input validationThe framework handles iteration, validation, grouping by composite key
{endpoint, method, headers, params}, strategy application, multiplexed event merging, error taxonomy, and REST envelope formatting.Architecture
Feature flag
Per-destination env var:
{DEST}_BATCHING_FRAMEWORK_ENABLED_WORKSPACE_IDS"ws-123,ws-456"— enables for specific workspaces"ALL"— enables for all workspacesOR logic with
batchedDestinationsMap:batchedDestinationsMap— always uses new path regardless of env varAny changes to existing capabilities/behaviour, mention the reason & what are the changes?
FetchHandlergainsbatchDestinationHandlerMapandgetBatchDestinationHandler()for caching integration class constructorsMiscServicegainsgetBatchDestinationHandler()for dynamic module resolutiondoRouterTransformation()innativeIntegration.tschecks the feature flag per destination group — when disabled, behaviour is identical to beforeAny new dependencies introduced with this change?
No. Uses existing dependencies:
zod,fast-json-stable-stringify.Any new generic utility introduced or modified. Please explain the changes.
BatchDestination<TBody>src/services/destination/nativeBatching/batchDestination.tsChunkBatchStrategysrc/services/destination/nativeBatching/chunkBatchStrategy.tsCustomBatchStrategysrc/services/destination/nativeBatching/customBatchStrategy.tsprocessBatchedDestination()src/services/destination/nativeBatching/processBatchedDestination.tsisBatchingFrameworkEnabled()src/constants/batchedDestinationsMap.tsBodyFormatenumsrc/services/destination/nativeBatching/types.tsReuses existing:
combineBatchRequestsWithSameJobIds,groupRouterTransformEvents,handleRouterTransformSuccessEvents,generateErrorObject.Any technical or performance related pointers to consider with the change?
new IntegrationClass(destination)per request to avoid race conditions with mutable state (important for destinations with dedup stores)maxPayloadSizemeasures the wrapped body size (wrapBody([...current, candidate])) before appending, ensuring accurate size limitsgenerateErrorObjectfor consistent error classification with properstatTags(errorCategory, errorType)dont_batch_events,batch_size(histogram), andoutput_batchesfor monitoring batching efficiency@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.