Skip to content

refactor: onboard batching framework - #5093

Merged
ItsSudip merged 11 commits into
developfrom
INT-6025/feat/addBatchingFramework
Apr 2, 2026
Merged

ItsSudip merged 11 commits into
developfrom
INT-6025/feat/addBatchingFramework

Conversation

@ItsSudip

@ItsSudip ItsSudip commented Mar 30, 2026 •

Copy link
Copy Markdown
Member

What are the changes introduced in this PR?

Introduces a generic Native Batching Framework for the /routerTransform route 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 processRouterDest with duplicated batching logic — chunking, size limits, metadata alignment, and error handling. This framework extracts that into a reusable BatchDestination<TBody> abstract class so destinations only implement:

  • transformEvent() — per-event transformation
  • getBatchStrategy() — returns a ChunkBatchStrategy or CustomBatchStrategy instance
  • getInputSchema() — Zod schema for integration-specific input validation

The framework handles iteration, validation, grouping by composite key {endpoint, method, headers, params}, strategy application, multiplexed event merging, error taxonomy, and REST envelope formatting.

Architecture

POST /routerTransform
  → doRouterTransformation()
    → isBatchingFrameworkEnabled(destType, workspaceId)?
      YES → processBatchedDestination(events, IntegrationClass)
              1. Validate inputs (integration-specific Zod schema)
              2. Split on dontBatch flag
              3. transformEvents() → transformEvent() per event
              4. Filter failed jobIds from payloads (multiplexing safety)
              5. Group batchable payloads by {endpoint, method, headers, params}
              6. Apply BatchStrategy (ChunkBatchStrategy / CustomBatchStrategy)
              7. Convert to server format (BodyFormat enum: JSON/JSON_ARRAY/XML/FORM)
              8. Merge multiplexed events (combineBatchRequestsWithSameJobIds)
      NO  → legacy processRouterDest() path (unchanged)

Feature flag

Per-destination env var: {DEST}_BATCHING_FRAMEWORK_ENABLED_WORKSPACE_IDS

  • Comma-separated workspace IDs: "ws-123,ws-456" — enables for specific workspaces
  • "ALL" — enables for all workspaces
  • Not set / empty — disabled (legacy path)

OR logic with batchedDestinationsMap:

  • Pre-GA: env var controls rollout per workspace
  • GA: add destination to batchedDestinationsMap — always uses new path regardless of env var

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

  • FetchHandler gains batchDestinationHandlerMap and getBatchDestinationHandler() for caching integration class constructors
  • MiscService gains getBatchDestinationHandler() for dynamic module resolution
  • doRouterTransformation() in nativeIntegration.ts checks the feature flag per destination group — when disabled, behaviour is identical to before

Any 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.

Utility File Purpose
BatchDestination<TBody> src/services/destination/nativeBatching/batchDestination.ts Abstract class destinations extend
ChunkBatchStrategy src/services/destination/nativeBatching/chunkBatchStrategy.ts Strategy class for array chunking with maxItems/maxPayloadSize
CustomBatchStrategy src/services/destination/nativeBatching/customBatchStrategy.ts Strategy class for custom merge/dedup logic
processBatchedDestination() src/services/destination/nativeBatching/processBatchedDestination.ts Orchestration: validate → transform → group → batch → format
isBatchingFrameworkEnabled() src/constants/batchedDestinationsMap.ts Per-destination feature flag (env var OR registry)
BodyFormat enum src/services/destination/nativeBatching/types.ts Controls HTTP body envelope format (JSON/JSON_ARRAY/XML/FORM)

Reuses existing: combineBatchRequestsWithSameJobIds, groupRouterTransformEvents, handleRouterTransformSuccessEvents, generateErrorObject.

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

  • Per-call instantiation: new IntegrationClass(destination) per request to avoid race conditions with mutable state (important for destinations with dedup stores)
  • Prospective byte sizing: maxPayloadSize measures the wrapped body size (wrapBody([...current, candidate])) before appending, ensuring accurate size limits
  • Multiplexing safety: if a multiplexed event (one jobId producing payloads at multiple endpoints) partially fails, the failed jobId is removed from all success payloads before batching — preventing partial delivery
  • Error taxonomy: uses generateErrorObject for consistent error classification with proper statTags (errorCategory, errorType)
  • Metrics: emits dont_batch_events, batch_size (histogram), and output_batches for 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.

🔒 Scanned for secrets using gitleaks 8.28.0
@ItsSudip
ItsSudip requested review from a team as code owners March 30, 2026 09:31
@coderabbitai

coderabbitai Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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

Walkthrough

Adds a feature‑gated destination batching framework: constants & gating, router-transform handler dynamic loading with caching, new router integration abstractions and batch strategies, an orchestration pipeline to build batched requests, native-integration gating, and comprehensive unit tests.

Changes

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning 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.

❤️ Share

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between c916c22 and 156a677.

⛔ Files ignored due to path filters (1)
  • test/integrations/destinations/posthog/router/batchingFramework.test.ts is excluded by !**/test/**
📒 Files selected for processing (9)
  • src/constants/batchedDestinationsMap.ts
  • src/helpers/fetchHandlers.ts
  • src/services/destination/__tests__/batchingFrameworkFeatureFlag.test.ts
  • src/services/destination/__tests__/processBatchedDestination.test.ts
  • src/services/destination/__tests__/routerIntegration.test.ts
  • src/services/destination/nativeIntegration.ts
  • src/services/destination/processBatchedDestination.ts
  • src/services/destination/routerIntegration.ts
  • src/services/misc.ts

🔒 Scanned for secrets using gitleaks 8.28.0
@codecov

codecov Bot commented Mar 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.40092% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.23%. Comparing base (c916c22) to head (496dbe0).
⚠️ Report is 8 commits behind head on develop.

Files with missing lines Patch % Lines
src/helpers/fetchHandlers.ts 11.11% 8 Missing ⚠️
...nation/nativeBatching/processBatchedDestination.ts 93.51% 7 Missing ⚠️
...s/destination/nativeBatching/chunkBatchStrategy.ts 88.88% 3 Missing ⚠️
src/services/destination/nativeIntegration.ts 81.81% 2 Missing ⚠️
src/services/misc.ts 0.00% 2 Missing ⚠️
...ces/destination/nativeBatching/batchDestination.ts 95.65% 1 Missing ⚠️
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.
📢 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/services/destination/routerIntegration.ts (1)

224-240: ⚠️ Potential issue | 🟠 Major

Default second-pass dontBatch failures 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.ts the retry flow intentionally uses 500 for the first failure and 400 after metadata.dontBatch=true 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 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4997199 and bace22d.

📒 Files selected for processing (4)
  • src/services/destination/__tests__/routerIntegration.test.ts
  • src/services/destination/nativeIntegration.ts
  • src/services/destination/processBatchedDestination.ts
  • src/services/destination/routerIntegration.ts
✅ Files skipped from review due to trivial changes (1)
  • src/services/destination/tests/routerIntegration.test.ts

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test pos 233

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test pos 229

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test pos 230

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test pos 231

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test pos 232

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test pos 233

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Design review focused on extensibility ahead of onboarding multiple destinations.

Comment thread src/constants/batchedDestinationsMap.ts Resolved

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@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.

🧹 Nitpick comments (1)
src/services/destination/routerIntegration.ts (1)

63-69: Consider validating that at least one of maxSize or maxBytes is provided in chunk() factory.

A ChunkStrategy with neither maxSize nor maxBytes would 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

📥 Commits

Reviewing files that changed from the base of the PR and between bace22d and 84d1462.

📒 Files selected for processing (1)
  • src/services/destination/routerIntegration.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (3)
src/services/destination/routerIntegration.ts (2)

225-242: ⚠️ Potential issue | 🟠 Major

Preserve the 400-on-second-pass retry behavior.

When transformEvent() throws for an input that already has metadata.dontBatch === true, Line 239 still falls back to the generic status from generateErrorObject(). 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.ts failures after metadata.dontBatch=true return 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 | 🟠 Major

Allow 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 out JSON_ARRAY. That makes array-body APIs awkward to onboard and weakens the “generic” contract. A shared RequestPayload = 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 | 🟠 Major

Reuse the normal batching flow inside the dontBatch loop.

Line 174 emits one request per transformed payload. That skips customBatch entirely and also prevents chunk strategies from regrouping multiple payloads produced by the same input into one request. dontBatch should 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

📥 Commits

Reviewing files that changed from the base of the PR and between 84d1462 and 7536e9f.

📒 Files selected for processing (7)
  • src/constants/batchedDestinationsMap.ts
  • src/helpers/fetchHandlers.ts
  • src/services/destination/__tests__/processBatchedDestination.test.ts
  • src/services/destination/__tests__/routerIntegration.test.ts
  • src/services/destination/processBatchedDestination.ts
  • src/services/destination/routerIntegration.ts
  • src/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

Comment thread src/constants/batchedDestinationsMap.ts Resolved
Comment thread src/constants/batchedDestinationsMap.ts Resolved
Comment thread src/constants/batchedDestinationsMap.ts Resolved
Comment thread src/helpers/fetchHandlers.ts Resolved
ItsSudip added 2 commits April 1, 2026 08:40
🔒 Scanned for secrets using gitleaks 8.28.0
🔒 Scanned for secrets using gitleaks 8.28.0

@shekhar-rudder shekhar-rudder left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chore -> refactor

@ItsSudip ItsSudip changed the title chore: onboard batching framework refactor: onboard batching framework Apr 1, 2026
🔒 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
@ItsSudip
ItsSudip requested a review from shekhar-rudder April 2, 2026 05:06
@sonarqubecloud

sonarqubecloud Bot commented Apr 2, 2026

Copy link
Copy Markdown

@ItsSudip
ItsSudip merged commit f6a7824 into develop Apr 2, 2026
29 checks passed
@ItsSudip
ItsSudip deleted the INT-6025/feat/addBatchingFramework branch April 2, 2026 05:41
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