Skip to content

fix: algolia proxy handler - #4600

Merged
maheshkutty merged 5 commits into
developfrom
fix.algolia_proxy
Sep 15, 2025
Merged

maheshkutty merged 5 commits into
developfrom
fix.algolia_proxy

Conversation

@maheshkutty

@maheshkutty maheshkutty commented Sep 1, 2025 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

This pull request refactors the Algolia destination response handling logic in the v1 API to improve error reporting for batch and individual events, and updates related test scenarios to match the new behavior. The main changes ensure that error responses are handled more consistently, especially when the dontBatch flag is set, and that test cases accurately reflect these changes.

Response handling improvements:

  • Refactored the responseHandler in src/v1/destinations/algolia/networkHandler.js to return a 200 status with detailed per-event responses in error cases, and to use the original status code for events with dontBatch=true. This improves clarity and accuracy when reporting errors for batch and individual events. [1] [2]

Test scenario updates:

  • Updated business test scenarios in test/integrations/destinations/algolia/dataDelivery/business.ts to expect the new response format, including clearer error messages and correct status codes for events with and without dontBatch. Added a new scenario to specifically test handling when dontBatch=true. [1] [2] [3] [4] [5] [6]

  • Changed test data in test/integrations/destinations/algolia/dataDelivery/other.ts so that the dontBatch flag is set to false for relevant scenarios, ensuring tests align with the new response logic. [1] [2] [3] [4] [5]

These changes make error handling more robust and predictable, especially in complex batch scenarios, and ensure that tests accurately validate the new logic.

What is the related Linear task?

Resolves INT-3505

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

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

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

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

N/A

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

@maheshkutty
maheshkutty requested a review from a team September 1, 2025 12:48
@coderabbitai

coderabbitai Bot commented Sep 1, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Per-item error reporting for Algolia requests in batches, providing clearer visibility into which items succeeded or failed.
  • Bug Fixes
    • Correct handling of single-item and multi-item payloads to prevent misreporting.
    • Eliminated inconsistent 422-specific behavior for more predictable responses.
  • Improvements
    • More consistent partial-success responses with clear error messages.
    • Enhanced retry categorization for network-related failures.
    • No breaking changes; existing integrations continue to work as before.

Walkthrough

Normalizes incoming rudderJobMetadata into an array and builds per-metadata response objects via mapping for 2xx, 4xx, and other non-2xx paths; removes the 422-specific branch and in-place metadata mutation; preserves the exported networkHandler signature. (49 words)

Changes

Cohort / File(s) Summary
Algolia network handler
src/v1/destinations/algolia/networkHandler.js
Remove top ESLint disable; add destType to destructuring; normalize rudderJobMetadata into metaDataArray; replace per-iteration metadata mutation with metaDataArray.map to produce per-metadata { statusCode, metadata, error } for 2xx and non-2xx paths; unify 4xx to return HTTP 200 with "Request Processed with Errors" and per-item error objects (use statusCode 500 unless metadata.dontBatch); remove 422-specific branch; pass per-metadata error array to TransformerProxyError; keep networkHandler export/signature unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant networkHandler
  participant Algolia
  participant TransformerProxyError
  rect rgba(100,149,237,0.06)
    Client->>networkHandler: Send batched request (events + rudderJobMetadata)
    networkHandler->>networkHandler: normalize rudderJobMetadata -> metaDataArray
    networkHandler->>Algolia: send batched request
  end
  alt Algolia 2xx
    Algolia-->>networkHandler: success (2xx)
    networkHandler->>networkHandler: metaDataArray.map -> [{statusCode:200, metadata, error:'success'}]
    networkHandler-->>Client: 200 with per-metadata success objects
  else Algolia 4xx
    Algolia-->>networkHandler: client error (4xx) + errorMessage
    networkHandler->>networkHandler: metaDataArray.map -> per-metadata errors (status 500 unless dontBatch)
    networkHandler-->>Client: 200 "Request Processed with Errors" + per-metadata errors
  else Algolia other non-2xx
    Algolia-->>networkHandler: non-2xx error
    networkHandler->>TransformerProxyError: throw with per-metadata error array
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • sivashanmukh
  • chandumlg
  • koladilip
  • utsabc

Suggestion: add unit tests covering 2xx, 4xx, and other non-2xx flows verifying per-metadata response construction (including dontBatch behavior) and update tests that relied on prior 422-specific behavior.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "fix: algolia proxy handler" is concise and directly related to the main change in the PR (refactoring the Algolia proxy/handler behavior). It clearly indicates this is a bugfix and names the affected area, making it useful for quick scanning of history. It could be marginally more informative by mentioning "response handling" or tests updated, but that is optional.
Description Check ✅ Passed The PR description closely follows the repository template: it explains the code changes and test updates, cites the related Linear task (Resolves INT-3505), and includes the objectives section with non-applicable items marked as N/A. The description documents the response-handling behavior change and test adjustments and includes the developer checklist, though the checklist items are unchecked. Overall the content is complete and actionable for reviewers, with only minor housekeeping left.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix.algolia_proxy

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f50c597 and 2f4112d.

📒 Files selected for processing (1)
  • src/v1/destinations/algolia/networkHandler.js (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/v1/destinations/algolia/networkHandler.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Code Coverage
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64

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.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@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

🧹 Nitpick comments (3)
src/v1/destinations/algolia/networkHandler.js (3)

31-31: Broaden error message extraction for Algolia payload shapes

Algolia may return string messages or an errors[] array. Make parsing more robust to improve operator clarity.

-  const errorMessage = response?.error?.message || response?.message || 'unknown error format';
+  const errorMessage = typeof response === 'string'
+    ? response
+    : response?.error?.message
+      || response?.message
+      || response?.error
+      || (Array.isArray(response?.errors) && response.errors[0]?.message)
+      || 'unknown error format';

22-26: Propagate actual HTTP status and clear error in success mapping
In src/v1/destinations/algolia/networkHandler.js, update the success branch to use the real status and a null error:

-      response: metaDataArray.map((metadata) => ({
-        statusCode: 200,
-        metadata,
-        error: 'success',
-      })),
+      response: metaDataArray.map((metadata) => ({
+        statusCode: status,
+        metadata,
+        error: null,
+      })),

This ensures non-200 2xx codes (e.g. 201, 204) aren’t flattened to 200 and removes the misleading "success" string. Consider applying the same pattern across other v1 handlers for consistency.


56-60: Pass destination name to TransformerProxyError
In src/v1/destinations/algolia/networkHandler.js (around the throw new TransformerProxyError call), change the empty statTags argument ('') to 'ALGOLIA' so errors are properly tagged for telemetry.
(Optional) Mirror this change in other v1 destinations for consistency.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b50b749 and 6a28a9a.

⛔ Files ignored due to path filters (2)
  • test/integrations/destinations/algolia/dataDelivery/business.ts is excluded by !**/test/**
  • test/integrations/destinations/algolia/dataDelivery/other.ts is excluded by !**/test/**
📒 Files selected for processing (1)
  • src/v1/destinations/algolia/networkHandler.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v1/destinations/algolia/networkHandler.js
🧠 Learnings (3)
📓 Common learnings
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
src/v1/destinations/algolia/networkHandler.js (2)

11-28: Overall: solid refactor aligning with PR goals

Early 4xx return with per-metadata responses and preserving dontBatch semantics looks good. Success path is clearer and side-effect free.


32-46: Confirm retry logic based on individual event statuses
I grepped the repo for any consumers of responseHandler() or checks on the wrapper’s top-level status and found none. Ensure your upstream pipeline keys retries/drops off each response[].statusCode rather than the returned status.

@maheshkutty maheshkutty closed this Sep 1, 2025
@maheshkutty maheshkutty reopened this Sep 1, 2025
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Sep 1, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.78%. Comparing base (1fd6bbc) to head (2f4112d).
⚠️ Report is 15 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #4600   +/-   ##
========================================
  Coverage    91.78%   91.78%           
========================================
  Files          642      642           
  Lines        33951    33965   +14     
  Branches      8045     8047    +2     
========================================
+ Hits         31163    31176   +13     
- Misses        2536     2559   +23     
+ Partials       252      230   -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.

ItsSudip
ItsSudip previously approved these changes Sep 11, 2025
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

♻️ Duplicate comments (2)
src/v1/destinations/algolia/networkHandler.js (2)

15-15: Defensive metadata normalization to avoid runtime crashes (dup of earlier bot note).

rudderJobMetadata can be undefined/non-array, causing downstream metadata.dontBatch reads and object spreads to throw. Normalize safely.

-  const metaDataArray = Array.isArray(rudderJobMetadata) ? rudderJobMetadata : [rudderJobMetadata];
+  const metaDataArray = Array.isArray(rudderJobMetadata)
+    ? rudderJobMetadata.filter(Boolean)
+    : (rudderJobMetadata ? [rudderJobMetadata] : []);

32-46: Fix crash on undefined metadata and return 422 for 4xx responses

Location: src/v1/destinations/algolia/networkHandler.js:32-46

  • Coerce falsy metadata to {} before reading dontBatch or spreading to avoid runtime crashes.
  • Return top-level status 422 for 4xx per PR intent; per-event status should be status when md.dontBatch is truthy, otherwise 500.
-  if (status >= 400 && status < 500) {
-    return {
-      status: 200,
+  if (status >= 400 && status < 500) {
+    return {
+      status: 422,
       message: `[ALGOLIA Response V1 Handler] - Request Processed with Errors`,
       destinationResponse,
-      response: metaDataArray.map((metadata) => {
-        const statusCode = !metadata.dontBatch ? 500 : status;
-        return {
-          statusCode,
-          metadata: { ...metadata, dontBatch: true },
-          error: errorMessage,
-        };
-      }),
+      response: metaDataArray.map((metadata) => {
+        const md = (metadata && typeof metadata === 'object') ? metadata : {};
+        const statusCode = md.dontBatch ? status : 500;
+        return {
+          statusCode,
+          metadata: { ...md, dontBatch: true },
+          error: errorMessage,
+        };
+      }),
     };
   }

Run the test suite and router integration to confirm batch-invalid cases surface 422 at the top level while preserving per-event codes.

🧹 Nitpick comments (3)
src/v1/destinations/algolia/networkHandler.js (3)

22-26: Guard success-path metadata shape.

Avoid returning metadata: undefined; use a safe object to keep the contract consistent.

-      response: metaDataArray.map((metadata) => ({
-        statusCode: 200,
-        metadata,
-        error: 'success',
-      })),
+      response: metaDataArray.map((metadata) => ({
+        statusCode: 200,
+        metadata: (metadata && typeof metadata === 'object') ? metadata : {},
+        error: 'success',
+      })),

30-30: Comment clarity.

Nit: This applies only in the 4xx branch below; mention 4xx explicitly to avoid confusion with 5xx path.


56-60: Shield error-throw path from undefined metadata.

Preserve shape in TransformerProxyError details.

-    metaDataArray.map((metadata) => ({
-      statusCode: status,
-      metadata,
-      error: errorMessage,
-    })),
+    metaDataArray.map((metadata) => ({
+      statusCode: status,
+      metadata: (metadata && typeof metadata === 'object') ? metadata : {},
+      error: errorMessage,
+    })),
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa70c8b and 33c2f98.

⛔ Files ignored due to path filters (2)
  • test/integrations/destinations/algolia/dataDelivery/business.ts is excluded by !**/test/**
  • test/integrations/destinations/algolia/dataDelivery/other.ts is excluded by !**/test/**
📒 Files selected for processing (1)
  • src/v1/destinations/algolia/networkHandler.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v1/destinations/algolia/networkHandler.js
🧠 Learnings (2)
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

♻️ Duplicate comments (1)
src/v1/destinations/algolia/networkHandler.js (1)

15-15: Prevent TypeError on missing/invalid metadata; safely read dontBatch and avoid spreading undefined

rudderJobMetadata can be undefined/non-array, and metadata.dontBatch plus { ...metadata } will throw when metadata is undefined/null. Harden normalization and guard property access.

Apply:

-  const metaDataArray = Array.isArray(rudderJobMetadata) ? rudderJobMetadata : [rudderJobMetadata];
+  const metaDataArray = Array.isArray(rudderJobMetadata)
+    ? rudderJobMetadata.filter(Boolean)
+    : (rudderJobMetadata ? [rudderJobMetadata] : []);

-      response: metaDataArray.map((metadata) => {
-        const statusCode = !metadata.dontBatch ? 500 : status;
-        return {
-          statusCode,
-          metadata: { ...metadata, dontBatch: true },
-          error: errorMessage,
-        };
-      }),
+      response: metaDataArray.map((metadata) => {
+        const safeMeta = metadata && typeof metadata === 'object' ? metadata : {};
+        const statusCode = !(safeMeta && safeMeta.dontBatch) ? 500 : status;
+        return {
+          statusCode,
+          metadata: { ...safeMeta, dontBatch: true },
+          error: errorMessage,
+        };
+      }),

Also applies to: 37-44

🧹 Nitpick comments (3)
src/v1/destinations/algolia/networkHandler.js (3)

22-26: Success path per‑event response: normalize metadata to an object for consistent shape

Keeps downstream consumers from handling undefined metadata.

-      response: metaDataArray.map((metadata) => ({
+      response: metaDataArray.map((metadata) => ({
         statusCode: 200,
-        metadata,
+        metadata: (metadata && typeof metadata === 'object') ? metadata : {},
         error: 'success',
       })),

31-31: Handle plain‑string error bodies

Algolia (and proxies) may return a string body; current logic falls back to “unknown error format”.

-  const errorMessage = response?.error?.message || response?.message || 'unknown error format';
+  const errorMessage = typeof response === 'string'
+    ? response
+    : response?.error?.message || response?.message || 'unknown error format';

56-60: Throw path: coerce metadata to an object for consistency

Avoid leaking non-object/undefined metadata in error details.

-    metaDataArray.map((metadata) => ({
-      statusCode: status,
-      metadata,
-      error: errorMessage,
-    })),
+    metaDataArray.map((metadata) => ({
+      statusCode: status,
+      metadata: (metadata && typeof metadata === 'object') ? metadata : {},
+      error: errorMessage,
+    })),
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33c2f98 and 2b01ca7.

⛔ Files ignored due to path filters (2)
  • test/integrations/destinations/algolia/dataDelivery/business.ts is excluded by !**/test/**
  • test/integrations/destinations/algolia/dataDelivery/other.ts is excluded by !**/test/**
📒 Files selected for processing (1)
  • src/v1/destinations/algolia/networkHandler.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v1/destinations/algolia/networkHandler.js
🧠 Learnings (3)
📓 Common learnings
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
src/v1/destinations/algolia/networkHandler.js (1)

34-35: Confirm Algolia V1 4xx response contract is covered by tests.

Handler behavior (verified in src/v1/destinations/algolia/networkHandler.js):

      status: 200,
      message: `[ALGOLIA Response V1 Handler] - Request Processed with Errors`,

Per-event statusCode: 500 when metadata.dontBatch is not set; preserves original 4xx when metadata.dontBatch === true.

Add/verify unit tests asserting:

  • top-level envelope: status === 200 and message contains "Processed with Errors"
  • per-event statusCode === 500 when dontBatch not set
  • per-event preserves original 4xx when metadata.dontBatch === true

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

♻️ Duplicate comments (2)
src/v1/destinations/algolia/networkHandler.js (2)

12-16: Harden metadata normalization to avoid runtime crashes (null/undefined).

If rudderJobMetadata is null/undefined, metaDataArray becomes [undefined], and later .dontBatch access and object spread will throw. Normalize defensively.

Apply:

-  const metaDataArray = Array.isArray(rudderJobMetadata) ? rudderJobMetadata : [rudderJobMetadata];
+  const metaDataArray = Array.isArray(rudderJobMetadata)
+    ? rudderJobMetadata.filter(Boolean)
+    : (rudderJobMetadata ? [rudderJobMetadata] : []);

Optional: if there’s a shared helper, prefer CommonUtils.toArray(rudderJobMetadata) and filter falsy for consistency.


32-56: Guard metadata property access and use dynamic error type.

  • metadata.dontBatch and { ...metadata } will throw when metadata isn’t an object; guard it.
  • Use getDynamicErrorType(status) instead of hard‑coding 'retryable' for 4xx to align with existing error typing.
-      statTags: {
-        errorCategory: 'network',
-        errorType: 'retryable',
+      statTags: {
+        errorCategory: 'network',
+        errorType: getDynamicErrorType(status),
         destType,
         module: 'destination',
         implementation: 'native',
         feature: 'dataDelivery',
         destinationId: metaDataArray[0]?.destinationId || '',
         workspaceId: metaDataArray[0]?.workspaceId || '',
       },
-      response: metaDataArray.map((metadata) => {
-        const statusCode = !metadata.dontBatch ? 500 : status;
-        return {
-          statusCode,
-          metadata: { ...metadata, dontBatch: true },
-          error: errorMessage,
-        };
-      }),
+      response: metaDataArray.map((metadata) => {
+        const safeMeta = metadata && typeof metadata === 'object' ? metadata : null;
+        const dontBatch = !!(safeMeta && safeMeta.dontBatch);
+        const statusCode = dontBatch ? status : 500;
+        return {
+          statusCode,
+          metadata: safeMeta ? { ...safeMeta, dontBatch: true } : { dontBatch: true },
+          error: errorMessage,
+        };
+      }),
🧹 Nitpick comments (1)
src/v1/destinations/algolia/networkHandler.js (1)

66-70: Prevent undefined metadata in thrown error payload.

Ensure thrown payload doesn’t include undefined and won’t crash consumers expecting objects.

-    metaDataArray.map((metadata) => ({
-      statusCode: status,
-      metadata,
-      error: errorMessage,
-    })),
+    metaDataArray.map((metadata) => {
+      const safeMeta = metadata && typeof metadata === 'object' ? metadata : null;
+      return {
+        statusCode: status,
+        metadata: safeMeta || {},
+        error: errorMessage,
+      };
+    }),
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b01ca7 and b6f44c4.

⛔ Files ignored due to path filters (1)
  • test/integrations/destinations/algolia/dataDelivery/business.ts is excluded by !**/test/**
📒 Files selected for processing (1)
  • src/v1/destinations/algolia/networkHandler.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v1/destinations/algolia/networkHandler.js
🧠 Learnings (2)
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
🧬 Code graph analysis (1)
src/v1/destinations/algolia/networkHandler.js (1)
src/v0/destinations/marketo/util.js (1)
  • rudderJobMetadata (219-219)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
src/v1/destinations/algolia/networkHandler.js (2)

22-27: Success path looks good; per‑event responses are consistent.


37-45: Verify statTags fields and categories.

Are destinationId/workspaceId guaranteed at the top level of metadata for Algolia? In many destinations these live under destInfo. Also confirm errorCategory: 'network' is intended for all 4xx (e.g., 422 validation vs 429 rate limit).

Would you like a quick script to scan usages of workspaceId/destinationId on rudderJobMetadata across the repo?

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

♻️ Duplicate comments (2)
src/v1/destinations/algolia/networkHandler.js (2)

15-15: Harden metadata normalization (avoid [undefined] and non-objects)

Current logic can yield [undefined], causing a crash when spreading metadata later. Normalize defensively.

-  const metaDataArray = Array.isArray(rudderJobMetadata) ? rudderJobMetadata : [rudderJobMetadata];
+  const metaDataArray = Array.isArray(rudderJobMetadata)
+    ? rudderJobMetadata.filter((m) => m && typeof m === 'object')
+    : (rudderJobMetadata && typeof rudderJobMetadata === 'object' ? [rudderJobMetadata] : []);

If CommonUtils.toArray exists, prefer it and then apply the same .filter(...).


32-55: Fix crash on undefined metadata; use correct errorType; guard destType

  • Spreading metadata (Line 51) throws when metadata is null/undefined.
  • Accessing metadata.dontBatch (Line 48) can throw.
  • errorType is hardcoded to 'retryable' for all 4xx; prefer getDynamicErrorType(status) for accuracy (e.g., 400 vs 429).
  • destType.toUpperCase() (Line 40) can throw if destType is falsy.

Apply:

       statTags: {
-        errorCategory: 'network',
-        errorType: 'retryable',
-        destType: destType.toUpperCase(),
+        errorCategory: 'network',
+        errorType: getDynamicErrorType(status),
+        destType: (destType || '').toUpperCase(),
         module: 'destination',
         implementation: 'native',
         feature: 'dataDelivery',
         destinationId: metaDataArray[0]?.destinationId || '',
         workspaceId: metaDataArray[0]?.workspaceId || '',
       },
-      response: metaDataArray.map((metadata) => {
-        const statusCode = !metadata.dontBatch ? 500 : status;
-        return {
-          statusCode,
-          metadata: { ...metadata, dontBatch: true },
-          error: errorMessage,
-        };
-      }),
+      response: metaDataArray.map((metadata) => {
+        const safeMeta = (metadata && typeof metadata === 'object') ? metadata : {};
+        const dontBatch = Boolean(safeMeta.dontBatch);
+        const statusCode = dontBatch ? status : 500;
+        return {
+          statusCode,
+          metadata: { ...safeMeta, dontBatch: true },
+          error: errorMessage,
+        };
+      }),
🧹 Nitpick comments (3)
src/v1/destinations/algolia/networkHandler.js (3)

12-12: Default destType to avoid downstream crash

destType can be absent; later toUpperCase() would throw. Default it here.

-  const { destinationResponse, rudderJobMetadata, destType } = responseParams;
+  const { destinationResponse, rudderJobMetadata, destType = '' } = responseParams;

30-30: Comment tweak for accuracy

Match the intended logic more precisely.

-  // If metadata.dontBatch is not set, use status 500, otherwise use the original status of destinationResponse because event already retried
+  // If metadata?.dontBatch !== true, use status 500; otherwise, preserve destinationResponse.status since the event has already been retried

66-70: Normalize metadata in thrown error path (consistency, safety)

Keep metadata an object to avoid consumer surprises and align with the 4xx path behavior.

-    metaDataArray.map((metadata) => ({
-      statusCode: status,
-      metadata,
-      error: errorMessage,
-    })),
+    metaDataArray.map((metadata) => ({
+      statusCode: status,
+      metadata: (metadata && typeof metadata === 'object') ? metadata : {},
+      error: errorMessage,
+    })),
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b6f44c4 and f50c597.

⛔ Files ignored due to path filters (1)
  • test/integrations/destinations/algolia/dataDelivery/business.ts is excluded by !**/test/**
📒 Files selected for processing (1)
  • src/v1/destinations/algolia/networkHandler.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v1/destinations/algolia/networkHandler.js
🧠 Learnings (3)
📓 Common learnings
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.

Applied to files:

  • src/v1/destinations/algolia/networkHandler.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
src/v1/destinations/algolia/networkHandler.js (1)

22-26: LGTM: predictable per‑event success responses

Mapping to per‑metadata 200s with a consistent “success” payload looks good.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

5 participants