Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Fix: Handle circular references in Http.request JSON processing #10744

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

alvidofaisal
Copy link

@alvidofaisal alvidofaisal commented Jun 14, 2025

PR Checklist

What is the current behavior?

JSON.stringify crashes when encountering circular references in Android Http.request responses or debug information containing circular structures (e.g., from CSS-like objects). This causes app crashes when processing HTTP responses that contain objects with circular references.

Additionally, the toJSON() method in HTTP responses had unnecessary performance overhead by converting already-parsed JavaScript objects to JSON strings and parsing them back.

What is the new behavior?

  • Introduced a safeJsonStringify utility that safely handles circular references by replacing them with "[Circular]" placeholders
  • Applied safeJsonStringify to HTTP response debug headers and request debug data to prevent crashes
  • Optimized the content.toJSON() method to return parsed objects directly without redundant stringify-parse cycles
  • Added comprehensive unit tests covering various circular reference scenarios including direct, nested, array-based, and toJSON method edge cases

Fixes/Implements/Closes #[Issue Number].

#10712

Summary by CodeRabbit

  • New Features
    • Added a utility for safely converting complex or circular objects to JSON strings.
  • Bug Fixes
    • Improved the reliability of debug information for HTTP requests and responses by ensuring headers and request content are safely serialized.
  • Tests
    • Introduced comprehensive tests to verify safe JSON stringification, especially with circular references and edge cases.

Introduces a `safeJsonStringify` utility to prevent crashes when `JSON.stringify` encounters circular references. This issue was particularly noted in Android when Http.request responses or debug information containing circular structures (e.g., from CSS-like objects) were processed.

The `safeJsonStringify` utility replaces circular references with `"[Circular]"`.

This commit applies `safeJsonStringify` to:

- The `content.toJSON()` method in `packages/core/http/http-request/index.android.ts` to safely parse HTTP response bodies.

- The debug data generation in `packages/core/http/http-request/index.android.ts` for `requestWillBeSent` and `responseReceived` events, ensuring headers and FormData content are safely stringified for the debugger.

Additionally, unit tests for `safeJsonStringify` have been added in `packages/core/utils/safe-json-stringify.spec.ts` to cover various scenarios, including direct and nested circular references, and handling of `toJSON` methods.
…JSON method

Eliminates unnecessary performance overhead by returning parseJSON(str) directly instead of converting the already-parsed JavaScript object to a JSON string and then parsing it back. HTTP response data doesn't contain circular references that would require safeJsonStringify processing.

Signed-off-by: alvidofaisal <[email protected]>
Copy link

coderabbitai bot commented Jun 14, 2025

Walkthrough

A new utility, safeJsonStringify, is introduced to serialize JavaScript objects to JSON while safely handling circular references. This utility is used in the Android HTTP request implementation to robustly serialize headers and request content for debugging. Comprehensive tests for safeJsonStringify are also added.

Changes

File(s) Change Summary
packages/core/utils/safe-json-stringify.ts Added safeJsonStringify utility for JSON serialization with circular reference handling.
packages/core/utils/safe-json-stringify.spec.ts Added test suite covering various scenarios and edge cases for safeJsonStringify.
packages/core/http/http-request/index.android.ts Updated to use safeJsonStringify for serializing headers and request content in debug information.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant HTTPRequest
    participant safeJsonStringify

    Caller->>HTTPRequest: Initiate HTTP request
    HTTPRequest->>safeJsonStringify: Serialize headers/content for debugging
    safeJsonStringify-->>HTTPRequest: Return safe JSON string
    HTTPRequest-->>Caller: Complete request with debug info
Loading

Poem

In the warren of code, a bug hops near,
Circular loops once filled us with fear.
Now with safe stringifies,
Our debug info flies—
No more infinite JSON, the path is clear!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-14T21_09_55_736Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • 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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
packages/core/http/http-request/index.android.ts (2)

97-105: Double parse / stringify is wasteful

JSON.parse(safeJsonStringify(headers)) incurs two passes over the same object just to deep-clone & de-circularise.
A shallow header object rarely needs deep traversal and never holds circular refs by spec.

-const safeDebugHeaders = JSON.parse(safeJsonStringify(headers));
+const safeDebugHeaders = { ...headers }; // headers are already plain key-value pairs

If genuine circularity is still possible, keep the safer version but gate it behind a cheap check:

const safeDebugHeaders =
  Object.values(headers).some(v => typeof v === 'object')
    ? JSON.parse(safeJsonStringify(headers))
    : { ...headers };

280-304: Lost request body fidelity

FormData and ArrayBuffer are reduced to either an almost empty object ({} after stringify) or the placeholder "[ArrayBuffer]".
This makes network-debugger output far less useful.

Suggestion:

-} else if (options.content instanceof FormData) {
-    (request as any).postData = safeJsonStringify(options.content);
+} else if (options.content instanceof FormData) {
+    // Iterate entries to build a readable representation
+    const fd: Record<string, unknown[]> = {};
+    options.content.forEach((v, k) => {
+        (fd[k] ||= []).push(typeof v === 'object' ? '[Object]' : v);
+    });
+    (request as any).postData = safeJsonStringify(fd);
 ...
-} else if (options.content instanceof ArrayBuffer) {
-    (request as any).postData = '[ArrayBuffer]';
+} else if (options.content instanceof ArrayBuffer) {
+    (request as any).postData = `ArrayBuffer(${options.content.byteLength} bytes)`;
 }

This preserves safety while giving developers actionable insight.

packages/core/utils/safe-json-stringify.spec.ts (2)

46-51: Spec comment block can be removed or turned into it.todo

Lines 47-73 contain in-test commentary explaining potential mismatches; leaving this prose in the production test adds noise.

Convert to separate describe/it blocks or delete after deciding desired behaviour.


74-75: Assertion may mask real behaviour

If safeJsonStringify(undefined) is changed (see utility review) this expectation will fail.
Either split into its own it with explicit rationale or assert using toBeUndefined() to track intended semantics.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8979ad8 and 8dbda20.

📒 Files selected for processing (3)
  • packages/core/http/http-request/index.android.ts (3 hunks)
  • packages/core/utils/safe-json-stringify.spec.ts (1 hunks)
  • packages/core/utils/safe-json-stringify.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/core/http/http-request/index.android.ts (2)
packages/core/utils/safe-json-stringify.ts (1)
  • safeJsonStringify (1-15)
packages/core/http/http-request/index.ios.ts (1)
  • request (75-233)
packages/core/utils/safe-json-stringify.spec.ts (1)
packages/core/utils/safe-json-stringify.ts (1)
  • safeJsonStringify (1-15)

@CatchABus
Copy link
Contributor

To be frank, I don't see why core needs this handling. Also, are there any http libraries that do this to begin with?
Normally, users should be able to convert the response to text and handle the parsing themselves.

@alvidofaisal
Copy link
Author

I figured since .toJSON() is already there in core, making it tougher against these circular reference crashes would be a good thing. It directly tackles that crash in issue #10712.

Totally agree, you can always grab the raw text. This just makes the helper itself a bit safer for folks who use it, so it doesn't unexpectedly break the app. Just trying to make it a bit more solid for that common case.

@CatchABus
Copy link
Contributor

CatchABus commented Jun 15, 2025

I figured since .toJSON() is already there in core, making it tougher against these circular reference crashes would be a good thing. It directly tackles that crash in issue #10712.

Totally agree, you can always grab the raw text. This just makes the helper itself a bit safer for folks who use it, so it doesn't unexpectedly break the app. Just trying to make it a bit more solid for that common case.

I see your point here but I believe there's a benefit of leaving the handling of that case to developers.
Let's say your REST API is in production but you have a circular reference in your json response you're not aware of.
The way things are now, client will let you know that something is wrong with your API JSON response and you can decide whether you'll take care of it. App breaking or crashing is not necessarily a bad thing in this case because it informs you about something possibly being wrong on the other side.

Personally, I always avoid circular refs and if I really need them then I try things like defining them as non-enumerable properties in my json objects.

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