Skip to content

fix: fireHTTPStats to emit metrics about requests only - #4635

Merged
koladilip merged 1 commit into
developfrom
fix/simplify-fireHTTPStats-metadata-handling
Sep 15, 2025
Merged

koladilip merged 1 commit into
developfrom
fix/simplify-fireHTTPStats-metadata-handling

Conversation

@koladilip

@koladilip koladilip commented Sep 13, 2025 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

Fixed fireHTTPStats to fire only once per request instead of for each job. The function was incorrectly processing metadata arrays and calling fireOutgoingReqStats multiple times per request.

What is the related Linear task?

N/A

Please explain the objectives of your changes below

The fireHTTPStats function was incorrectly firing stats for each job in the metadata array instead of once per request. This change fixes the behavior by:

  • Removing the complex metadata array processing logic that was causing multiple stats calls
  • Passing metadata directly to fireOutgoingReqStats as a single value
  • Ensuring fireHTTPStats fires only once per request, not per job
  • Updating all related tests to reflect the corrected behavior
  • Adding comprehensive test coverage for various metadata types (null, string, boolean, complex objects, mixed arrays)

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

Bug Fix: The function now correctly calls fireOutgoingReqStats only once per request instead of multiple times for each job in the metadata array. This fixes the incorrect stats reporting behavior.

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?

  • Fixed incorrect stats reporting (was firing per job, now fires per request)
  • Reduced function complexity and improved maintainability
  • Single call to fireOutgoingReqStats instead of multiple calls for array metadata
  • Better test coverage for edge cases

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

@koladilip
koladilip requested a review from a team September 13, 2025 05:17
@coderabbitai

coderabbitai Bot commented Sep 13, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • More consistent and streamlined telemetry: emits a single timing event per request, regardless of metadata shape.
  • Bug Fixes
    • Improved handling of missing or null metadata to avoid errors and noise in metrics.
    • More reliable status code reporting in metrics for both success and error cases.
    • Cleaner log metadata by filtering out null/undefined entries.
  • Refactor
    • Simplified metrics flow with sensible defaults to reduce duplicate events.
  • Tests
    • Expanded coverage across diverse metadata scenarios to ensure consistent behavior.
✨ 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/simplify-fireHTTPStats-metadata-handling

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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.

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed The PR description follows the repository template and clearly explains the change, objectives, testing updates, and the bug fix rationale; it documents that fireHTTPStats now fires once per request and lists test coverage and developer checklist items. However the "related Linear task" field is marked "N/A" while the template expects a "Resolves INT-XXX" entry and the documentation-change status is left uncertain, which should be clarified.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Title Check ✅ Passed The title correctly targets the changed function and the general intent (fixing metric emission from fireHTTPStats), so it is related to the changeset; however it is somewhat generic and does not describe the core behavioral change—simplified metadata handling and emitting a single outgoing metric per request.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/adapters/network.js (1)

8-8: Fix ESLint error: remove unused import.

isDefinedAndNotNull is unused and breaks the Verify job.

Apply:

-const { isDefinedAndNotNull, PlatformError } = require('@rudderstack/integrations-lib');
+const { PlatformError } = require('@rudderstack/integrations-lib');
🧹 Nitpick comments (5)
src/adapters/network.js (3)

85-101: Single-call semantics: good simplification; align observability.

Change is clear and reduces complexity. Please notify owners of dashboards/alerts relying on per-metadata fan-out so they can adjust expectations and thresholds.


87-88: Edge-case: network errors without response.status.

For successful paths, response.status should exist, but adding a safe default keeps tags consistent if any custom client returns a truthy success without status.

-  const statusCode = clientResponse.success
-    ? clientResponse.response?.status
+  const statusCode = clientResponse.success
+    ? (clientResponse.response?.status ?? 200)
     : getErrorStatusCode(clientResponse.response);

90-100: Minor readability: deconstruct statTags once.

Reduces repetition and keeps the call-site compact.

-  fireOutgoingReqStats({
-    destType: statTags.destType || '',
-    feature: statTags.feature || '',
-    endpointPath: statTags.endpointPath || '',
-    requestMethod: statTags.requestMethod || '',
-    module: statTags.module || '',
-    metadata: statTags.metadata,
+  const {
+    destType = '',
+    feature = '',
+    endpointPath = '',
+    requestMethod = '',
+    module: moduleTag = '',
+    metadata,
+  } = statTags || {};
+
+  fireOutgoingReqStats({
+    destType,
+    feature,
+    endpointPath,
+    requestMethod,
+    module: moduleTag,
+    metadata,
     statusCode,
     startTime,
     clientResponse,
   });
src/adapters/network.test.js (2)

139-176: Array metadata test updated: good; add counter assertion to cover status code path.

You’ve validated the single timing event. Also assert outgoing_request_count to exercise the new statusCode derivation.

     expect(stats.timing).toHaveBeenCalledTimes(1);
+    expect(stats.counter).toHaveBeenCalledTimes(1);
+    expect(stats.counter).toHaveBeenNthCalledWith(
+      1,
+      'outgoing_request_count',
+      1,
+      expect.objectContaining({
+        destType: 'DT',
+        feature: 'feat',
+        module: '',
+        endpointPath: '/some/url',
+        requestMethod: 'post',
+        success: false,
+        statusCode: 400,
+      }),
+    );

382-558: Additional shape tests: solid; consider one success-path counter assertion.

Great spread across null/string/boolean/complex/mixed. Add at least one assertion for stats.counter on a success case to ensure statusCode: 200 is emitted.

   expect(stats.timing).toHaveBeenCalledTimes(1);
+  expect(stats.counter).toHaveBeenCalledTimes(1);
+  expect(stats.counter).toHaveBeenNthCalledWith(
+    1,
+    'outgoing_request_count',
+    1,
+    expect.objectContaining({
+      destType: 'DT',
+      feature: 'feat',
+      module: '',
+      endpointPath: '/some/url',
+      requestMethod: 'post',
+      success: true,
+      statusCode: 200,
+    }),
+  );
📜 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 dbacf0a and 3c5c8ab.

📒 Files selected for processing (2)
  • src/adapters/network.js (1 hunks)
  • src/adapters/network.test.js (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

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

Files:

  • src/adapters/network.test.js
  • src/adapters/network.js
🧠 Learnings (1)
📚 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/adapters/network.test.js
🧬 Code graph analysis (2)
src/adapters/network.test.js (2)
src/v0/destinations/marketo_static_list/transform.js (1)
  • metadataArray (166-166)
src/adapters/network.js (6)
  • stats (9-9)
  • startTime (163-163)
  • clientResponse (116-116)
  • clientResponse (128-128)
  • clientResponse (151-151)
  • fireHTTPStats (85-101)
src/adapters/network.js (6)
src/v0/destinations/marketo/util.js (2)
  • clientResponse (250-257)
  • clientResponse (269-276)
src/v0/destinations/monday/util.js (1)
  • clientResponse (183-202)
src/adapters/utils/networkUtils.js (2)
  • clientResponse (136-136)
  • clientResponse (161-161)
src/cdk/v2/destinations/intercom/utils.js (3)
  • statTags (483-490)
  • statTags (537-543)
  • statTags (577-583)
src/v0/destinations/klaviyo/util.js (1)
  • statusCode (103-103)
src/v0/util/index.js (1)
  • getErrorStatusCode (1553-1567)
🪛 GitHub Actions: Verify
src/adapters/network.js

[error] 8-8: ESLint failed on command 'npx eslint src/adapters/network.js src/adapters/network.test.js --fix'. 'isDefinedAndNotNull' is assigned a value but never used. (no-unused-vars)

⏰ 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 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/adapters/network.test.js (2)

236-244: Edge-case coverage looks right.

Validates empty/mixed/null arrays map to a single timing event with base tags only. Nice.

Also applies to: 304-312


166-176: Expectation change to single emission: aligned with new behavior.

Assertion updated from 2 to 1 call is correct given the simplification.

- Remove complex metadata array processing logic
- Pass metadata directly to fireOutgoingReqStats
- Update tests to reflect simplified behavior
- Add comprehensive test coverage for various metadata types
@koladilip
koladilip force-pushed the fix/simplify-fireHTTPStats-metadata-handling branch from 3c5c8ab to 5c275d8 Compare September 13, 2025 05:25
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Sep 13, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.78%. Comparing base (2fd8412) to head (5c275d8).
⚠️ Report is 12 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #4635   +/-   ##
========================================
  Coverage    91.78%   91.78%           
========================================
  Files          642      642           
  Lines        33941    33943    +2     
  Branches      8042     8033    -9     
========================================
+ Hits         31153    31155    +2     
- Misses        2536     2558   +22     
+ 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.

@sonarqubecloud

Copy link
Copy Markdown

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/logger.js (1)

27-34: Add default in getLogger to satisfy ESLint and avoid undefined logger

Missing default can trip default-case/consistent-return and return undefined for unexpected values.

 const getLogger = () => {
   switch (loggerImpl) {
     case 'winston':
       return logger;
     case 'console':
       return console;
+    default:
+      return logger;
   }
 };
🧹 Nitpick comments (2)
src/logger.js (2)

36-40: Avoid shadowing outer logger in setLogLevel (no-shadow)

Rename the inner variable to prevent shadowing and silence lint.

 const setLogLevel = (level) => {
-  const logger = getLogger();
+  const currentLogger = getLogger();
   logLevel = level || logLevel;
-  logger?.setLogLevel(logLevel);
+  currentLogger?.setLogLevel(logLevel);
 };

49-52: Pick first non-null object via find; align with array handling in log()

Using filter(...)[0] scans the whole array and may select a non-object (e.g., string) ahead of a valid object. Prefer find and restrict to objects; fall back to first defined non-null if no object exists.

 let reqMeta = metadata;
 if (Array.isArray(metadata)) {
-    [reqMeta] = metadata.filter(isDefinedAndNotNull);
+    reqMeta =
+      metadata.find((m) => isDefinedAndNotNull(m) && typeof m === 'object' && !Array.isArray(m)) ??
+      metadata.find(isDefinedAndNotNull);
 }
📜 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 3c5c8ab and 5c275d8.

📒 Files selected for processing (3)
  • src/adapters/network.js (2 hunks)
  • src/adapters/network.test.js (7 hunks)
  • src/logger.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/adapters/network.test.js
  • src/adapters/network.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

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

Files:

  • src/logger.js
🧠 Learnings (1)
📚 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/logger.js
🧬 Code graph analysis (1)
src/logger.js (1)
src/v0/util/index.js (1)
  • isDefinedAndNotNull (51-51)
⏰ 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). (7)
  • 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: 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
  • GitHub Check: UT Tests
🔇 Additional comments (2)
src/logger.js (2)

2-6: Verify export: isDefinedAndNotNull from @rudderstack/integrations-lib

If the package version used by this repo doesn’t export isDefinedAndNotNull, ESLint’s import rules and runtime will fail. Please confirm the symbol exists in that package/version.


94-107: Confirm intent: array metadata logs multiple entries

This path logs once per object in metadata. Given the PR’s “single event” direction for HTTP stats, confirm whether logs should also be single-entry. If yes, consider collapsing to the first valid element.

-    if (Array.isArray(metadata)) {
-      metadata
-        .filter((m) => typeof m === 'object' && !Array.isArray(m))
-        .forEach((m) => {
-          logMethod(
-            message,
-            {
-              ...getLogMetadata(m),
-              ...otherLogInfoArgs,
-            },
-            ...otherArgs,
-          );
-        });
-      return;
-    }
+    if (Array.isArray(metadata)) {
+      const m =
+        metadata.find((x) => typeof x === 'object' && x !== null && !Array.isArray(x)) ??
+        metadata.find(isDefinedAndNotNull);
+      logMethod(
+        message,
+        {
+          ...getLogMetadata(m),
+          ...otherLogInfoArgs,
+        },
+        ...otherArgs,
+      );
+      return;
+    }

@koladilip koladilip changed the title fix: simplify fireHTTPStats metadata handling fix: fireHTTPStats to emit metrics about requests Sep 13, 2025
@koladilip koladilip changed the title fix: fireHTTPStats to emit metrics about requests fix: fireHTTPStats to emit metrics about requests only Sep 13, 2025
Comment thread src/adapters/network.js Resolved
@koladilip
koladilip merged commit 5d8932a into develop Sep 15, 2025
@koladilip
koladilip deleted the fix/simplify-fireHTTPStats-metadata-handling branch September 15, 2025 09:29
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.

4 participants