Skip to content
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

feat: resolve circular json serialization issue #382

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

Conversation

Harish-osmosys
Copy link
Contributor

@Harish-osmosys Harish-osmosys commented Jan 10, 2025

API PR Checklist

Pre-requisites

  • I have gone through the Contributing guidelines for Submitting a Pull Request (PR) and ensured that this is not a duplicate PR.
  • I have performed unit testing for the new feature added or updated to ensure the new features added are working as expected.
  • I have added/updated test cases to the test suite as applicable.
  • I have performed preliminary testing using the test suite to ensure that any existing features are not impacted and any new features are working as expected as a whole.
  • I have added/updated the required api docs as applicable.
  • I have added/updated the .env.example file with the required values as applicable.

PR Details

PR details have been updated as per the given format (see below)

  • PR title adheres to the format specified in guidelines (e.g., feat: add admin login endpoint)
  • Description has been added
  • Related changes have been added (optional)
  • Screenshots have been added (optional)
  • Query request and response examples have been added (as applicable, in case added or updated)
  • Documentation changes have been listed (as applicable)
  • Test suite/unit testing output is added (as applicable)
  • Pending actions have been added (optional)
  • Any other additional notes have been added (optional)

Additional Information

  • Appropriate label(s) have been added (ready for review should be added if the PR is ready to be reviewed)
  • Assignee(s) and reviewer(s) have been added (optional)

Note: Reviewer should ensure that the checklist and description have been populated and followed correctly, and the PR should be merged only after resolving all conversations and verifying that CI checks pass.


Description:

This Pr uses the new npm package stringify method instead of the json to avoid circular Json serialization issue

Related changes:

  • Add a new package flatted

Screenshots:

image

Query request and response:

N/A

Documentation changes:

N/A

Test suite/unit testing output:

N/A

Pending actions:

N/A

Additional notes:

N/A

Summary by CodeRabbit

  • New Features

    • Added flatted library to improve logging capabilities.
  • Improvements

    • Enhanced log serialization to better handle complex data structures, including circular references.
    • Modified logging approach for error handling and API response tracking.
  • Chores

    • Updated package dependencies to include flatted version 3.3.2.

@Harish-osmosys Harish-osmosys requested a review from xixas January 10, 2025 07:36
@Harish-osmosys Harish-osmosys self-assigned this Jan 10, 2025
Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request introduces the flatted package to the API project, focusing on enhancing logging capabilities. The changes involve replacing the standard JSON.stringify method with flatted.stringify in logging configurations and transport mechanisms. This modification improves the handling of complex objects with circular references during logging, particularly in the SlogerrTransport and logger configuration files.

Changes

File Change Summary
apps/api/package.json Added "flatted": "^3.3.2" dependency
apps/api/src/common/logger/slogerr.transport.ts - Imported stringify from flatted
- Replaced JSON.stringify(info) with stringify(info)
- Changed error logging from this.logger.error(...) to this.logger.warn(...)
apps/api/src/config/logger.config.ts - Added import for stringify from flatted
- Replaced JSON.stringify(logObject) with stringify(logObject) in log formatting

Sequence Diagram

sequenceDiagram
    participant Logger as Logging System
    participant Flatted as Flatted Library
    participant Transport as SlogerrTransport

    Logger->>Flatted: Request object serialization
    Flatted-->>Logger: Serialize with circular reference support
    Logger->>Transport: Pass serialized log object
    Transport->>Transport: Log object using flatted stringify
Loading

Poem

🐰 A Rabbit's Logging Tale 🌟
Circular refs, no longer a fright,
Flatted stringify brings logging delight!
From JSON's limits, we now break free,
Logging complex objects with glee
A hoppy solution, clean and bright! 🚀


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b9eb53a and 3f3c1aa.

📒 Files selected for processing (1)
  • apps/api/src/common/logger/slogerr.transport.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/api/src/common/logger/slogerr.transport.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

@Harish-osmosys Harish-osmosys changed the title feat: resolve circular JSON serialization issue feat: resolve circular json serialization issue Jan 10, 2025
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ca08424 and f89254d.

⛔ Files ignored due to path filters (1)
  • apps/api/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • apps/api/package.json (1 hunks)
  • apps/api/src/common/logger/slogerr.transport.ts (3 hunks)
  • apps/api/src/config/logger.config.ts (2 hunks)
🔇 Additional comments (3)
apps/api/src/common/logger/slogerr.transport.ts (1)

7-7: LGTM: Proper implementation of circular reference handling

The replacement of JSON.stringify with flatted.stringify is the correct approach to handle circular references in log objects.

Also applies to: 44-44

apps/api/src/config/logger.config.ts (1)

11-11: LGTM: Consistent use of circular reference handling

The implementation correctly uses flatted.stringify for log serialization, maintaining consistency with the transport implementation.

Also applies to: 43-43

apps/api/package.json (1)

54-54: Verify the flatted package version for known issues

The package version ^3.3.2 allows for minor updates. Let's verify this version for any known issues or vulnerabilities.

✅ Verification successful

Package version ^3.3.2 is safe to use

The package is actively maintained with no reported security issues or critical bugs. Recent GitHub activity shows regular updates and prompt issue resolution.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for security advisories and latest versions of the flatted package

# Check npm for latest versions
npm view flatted versions --json | jq -r '.[-5:]'

# Check for security advisories
npm audit [email protected] --json || true

Length of output: 740


Script:

#!/bin/bash
# Check GitHub releases and npm advisories for flatted package

# Get latest releases from GitHub
gh release list --repo lukeed/flatted --limit 5

# Direct check of npm advisories (alternative method)
curl -s "https://registry.npmjs.org/-/npm/v1/security/advisories/search?package=flatted" | jq .

# Get package description and repository info
npm view flatted repository.url description

Length of output: 511


Script:

#!/bin/bash
# Check GitHub activity and issues for WebReflection/flatted

# Get latest releases
gh release list --repo WebReflection/flatted --limit 5

# Check recent issues
gh issue list --repo WebReflection/flatted --state all --limit 5

# Get latest commit date
gh api repos/WebReflection/flatted/commits/master --jq '.commit.committer.date'

Length of output: 891

Comment on lines 69 to 72
this.logger.log(
`Failed to send log to Slogerr. Status: ${response.status}, Message: ${response.statusText}`,
);
} else {
Copy link

@coderabbitai coderabbitai bot Jan 10, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider keeping error level logging for failed requests

Changing from error to log level reduces the visibility of failed log submissions. Failed logging attempts should typically be treated as errors to ensure proper monitoring and alerting.

-          this.logger.log(
+          this.logger.error(
             `Failed to send log to Slogerr. Status: ${response.status}, Message: ${response.statusText}`,
           );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
this.logger.log(
`Failed to send log to Slogerr. Status: ${response.status}, Message: ${response.statusText}`,
);
} else {
this.logger.error(
`Failed to send log to Slogerr. Status: ${response.status}, Message: ${response.statusText}`,
);
} else {

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated in latest commit

Copy link

Choose a reason for hiding this comment

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

@Harish-osmosys Thank you for implementing the change. I can confirm that error-level logging has been restored for failed requests.

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the current content of the file
rg "Failed to send log to Slogerr" -A 2 "apps/api/src/common/logger/slogerr.transport.ts"

Length of output: 317


Script:

#!/bin/bash
# Check with more context lines
rg "Failed to send log to Slogerr" -B 2 -A 2 "apps/api/src/common/logger/slogerr.transport.ts"

Length of output: 424


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link
Contributor Author

@Harish-osmosys Harish-osmosys Jan 15, 2025

Choose a reason for hiding this comment

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

      this.logger.error(
         `Failed to send log to Slogerr. Status: ${response.status}, Message: ${response.statusText}`,
       );
       
       when i tried using this - if their was any issue in slogger config  wrong type or wrong api key - the error log is generated which due to the new transport again route to this slogger transport so the loop continue so to avoid this i have made this as a warn log only instead of error log

Copy link

Choose a reason for hiding this comment

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

@Harish-osmosys I apologize for my previous suggestion and thank you for the detailed explanation. You're absolutely right - using error logging here would create an infinite loop when there are configuration issues, as the error logs would keep getting routed back through the same transport. Your solution to use info logging is the correct approach to break this potential infinite loop.


✏️ Learnings added
Learnt from: Harish-osmosys
PR: OsmosysSoftware/osmo-x#382
File: apps/api/src/common/logger/slogerr.transport.ts:69-72
Timestamp: 2025-01-15T09:30:40.760Z
Learning: In the SlogerrTransport class (apps/api/src/common/logger/slogerr.transport.ts), failed attempts to send logs to Slogerr should use info-level logging (this.logger.log) instead of error-level logging to prevent infinite loops, as error logs would be routed back through the same transport when there are configuration issues.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

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

🧹 Nitpick comments (1)
apps/api/src/config/logger.config.ts (1)

Line range hint 1-1: Consider adding tests for circular reference handling.

While the implementation of flatted looks good, consider adding tests to verify:

  1. Circular reference handling in various log object structures
  2. Performance impact of using flatted vs JSON.stringify
  3. Error scenarios and their proper logging levels

This will ensure the changes are robust and maintainable.

Would you like me to help create test cases for these scenarios?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ca08424 and f89254d.

⛔ Files ignored due to path filters (1)
  • apps/api/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • apps/api/package.json (1 hunks)
  • apps/api/src/common/logger/slogerr.transport.ts (3 hunks)
  • apps/api/src/config/logger.config.ts (2 hunks)
🔇 Additional comments (5)
apps/api/package.json (1)

54-54: Verify the latest stable version of flatted.

The package addition looks good, but let's verify we're using the latest stable version.

✅ Verification successful

Package version is up to date

The installed version (^3.3.2) matches the latest version available on npm registry.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check latest version and security advisories for flatted
echo "Latest version from npm:"
npm view flatted version

echo -e "\nSecurity advisories:"
npm audit flatted

Length of output: 517

apps/api/src/common/logger/slogerr.transport.ts (2)

7-7: LGTM! Import looks good.

The import of stringify from flatted is correctly placed.


44-44: LGTM! Correctly using flatted for circular JSON handling.

The replacement of JSON.stringify with flatted's stringify will properly handle circular references in the log info object.

apps/api/src/config/logger.config.ts (2)

11-11: LGTM! Import looks good.

The import of stringify from flatted is correctly placed.


43-43: Verify circular reference handling in log objects.

The change to use flatted's stringify is good, but let's verify it handles all our log object structures correctly.

✅ Verification successful

The circular reference handling is verified but over-engineered for current usage

The codebase shows consistent use of simple log objects (strings, errors, basic objects) with no circular references. While flatted.stringify() will work correctly, it's more complex than needed since the current logging patterns don't involve circular references. Regular JSON.stringify() would suffice for all current use cases.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for complex log objects that might have circular references
echo "Searching for complex log objects:"
rg -B 5 -A 5 "logger\.(log|error|warn|debug|verbose)\(" --type ts

echo -e "\nSearching for custom logger implementations:"
ast-grep --pattern 'class $_ implements $_ {
  $$$
  logger$_ = $_
  $$$
}'

Length of output: 72755

apps/api/src/common/logger/slogerr.transport.ts Outdated Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant