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: add sentry integration #25

Merged
merged 4 commits into from
Feb 19, 2025
Merged

Feat: add sentry integration #25

merged 4 commits into from
Feb 19, 2025

Conversation

Benzbeeb
Copy link
Collaborator

@Benzbeeb Benzbeeb commented Feb 18, 2025

Summary by CodeRabbit

  • New Features

    • Integrated advanced error tracking and performance monitoring, ensuring improved diagnostics and stability through enhanced error handling.
  • Chores

    • Updated configuration settings to securely exclude sensitive environment files from version control.
  • Dependencies

    • Added new dependencies for Sentry's monitoring and profiling capabilities.

Copy link

coderabbitai bot commented Feb 18, 2025

Walkthrough

This pull request enhances the application’s error monitoring and performance tracking by integrating Sentry. Key updates include adding new Sentry dependencies in the package configuration and updating various source files to initialize Sentry, capture exceptions, and wrap critical operations with Sentry spans. Global error handlers have also been introduced to log unhandled exceptions and rejections. Additionally, the .gitignore file was updated to include environment variable files.

Changes

File(s) Change Summary
.gitignore Added +.env* pattern and modified -/test_db to +/test_db (no functional change).
package.json Added dependencies: @sentry/node (^8.51.0), @sentry/profiling-node (^8.51.0), and @sentry/tracing (^7.120.3).
src/db/controller/packet.ts, src/index.ts, src/lib/sentry.ts, src/lib/error-handlers.ts, src/workers/chain.ts, src/workers/wallet.ts Integrated Sentry for error tracking and performance monitoring. Updates include initializing Sentry in the main function, wrapping database queries in Sentry spans, adding functions (captureException, initSentry, setupErrorHandlers), and enhancing error handling in workers by capturing exceptions.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application (src/index.ts)
    participant Sentry as Sentry Module (src/lib/sentry.ts)
    participant DB as Database Query (PacketController)
    
    App->>Sentry: initSentry('rapid-relayer')
    Sentry-->>App: Initialization complete
    App->>DB: getSendPackets() (executes query)
    alt SENTRY_DSN is set
        DB->>Sentry: Wrap query in Sentry span
    else Not set
        DB-->>App: Execute query directly
    end
Loading
sequenceDiagram
    participant Process as Node Process
    participant ErrorHandler as Global Error Handlers (setupErrorHandlers)
    participant Sentry as captureException
    
    Process->>ErrorHandler: Unhandled exception/rejection or warning
    ErrorHandler->>Sentry: captureException(error)
    ErrorHandler-->>Process: Schedule process exit after delay
Loading

Suggested reviewers

  • ALPAC-4

Poem

I'm a little rabbit hopping through the code,
With ears alert for errors in every node.
Sentry catches troubles as I bound along,
Turning bugs to carrots, making our app strong.
Hop on, dear coders, with joy and delight—
Our code garden blooms in carrot-light!
🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

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 (10)
src/lib/sentry.ts (2)

6-22: Allow optional handling of flush failures.
Currently, flush failures are silently ignored. Consider logging or handling the error from Sentry.flush() to aid in debugging network or server issues and to confirm that the event was indeed sent to Sentry.

     await Sentry.flush(1000).catch(() => undefined)
+    // Optionally:
+    /*
+    await Sentry.flush(1000).catch((err) => {
+      console.error("Sentry flush failed:", err);
+    });
+    */

24-69: Avoid logging Sentry DSN for security reasons.
Exposing the DSN in logs could allow unauthorized event submissions. Consider masking it or omitting it entirely for better security practices.

 console.log(`Sentry initialized:
     server_name: ${serverName}
-    dsn: ${dsn}
+    dsn: [REDACTED]
     env: ${env || 'development'}
     ...
`)
src/lib/error-handlers.ts (3)

4-15: Ensure sufficient time for error reporting before exit.
Forcefully exiting the process with process.exit(1) may cut off Sentry’s flush if the system is heavily loaded. Consider a graceful shutdown strategy or a slightly longer timeout for critical systems.


17-23: Apply consistent approach for uncaught exceptions.
Same concern as unhandled rejections. A graceful shutdown or a longer delay may be preferable to ensure all resources are released properly.


25-27: Optionally capture process warnings.
If warnings correlate with relevant runtime issues, consider capturing them with Sentry for more comprehensive visibility.

 process.on('warning', (warning) => {
   console.warn('Process warning:', warning)
+  // Optionally capture to Sentry:
+  // void captureException(new Error(`Process warning: ${warning.message}`), 'warning')
 })
src/workers/chain.ts (2)

95-96: Consider creating a utility function for error handling.

The error handling pattern e instanceof Error ? e : new Error(String(e)) is repeated multiple times. Consider extracting it into a utility function for better maintainability.

+// In src/lib/error.ts
+export const normalizeError = (e: unknown): Error => 
+  e instanceof Error ? e : new Error(String(e));

+// In this file
-await captureException(e instanceof Error ? e : new Error(String(e)))
+await captureException(normalizeError(e))

223-230: Improve error message clarity in feedEvents.

The error message contains a typo and could be more descriptive.

-const errorMsg = `Fail to fecth block result. resonse - ${e}`
+const errorMsg = `Failed to fetch block result. Response: ${e}`
src/db/controller/packet.ts (1)

119-129: Consider centralizing Sentry configuration checks.

The SENTRY_DSN environment variable check could be moved to a central configuration utility to maintain consistency across the application.

+// In src/lib/sentry.ts
+export const isSentryEnabled = (): boolean => !!process.env.SENTRY_DSN;
+export const withSentrySpan = <T>(
+  operation: string,
+  name: string,
+  fn: () => T
+): T => {
+  if (!isSentryEnabled()) {
+    return fn();
+  }
+  return Sentry.startSpan(
+    {
+      op: operation,
+      name,
+    },
+    fn
+  );
+};

+// In this file
-if (!process.env.SENTRY_DSN) {
-  return executeQuery()
-}
-
-return Sentry.startSpan(
-  {
-    op: 'db.query',
-    name: 'getSendPackets',
-  },
-  executeQuery
-)
+return withSentrySpan('db.query', 'getSendPackets', executeQuery)
src/workers/wallet.ts (2)

49-51: Structure error handling consistently.

The error handling could be more structured and consistent with other parts of the application.

-await captureException(e instanceof Error ? e : new Error(String(e)))
-this.logger.error(`[run] ${e}`)
+const error = normalizeError(e);
+await captureException(error);
+this.logger.error(`[run] ${error.message}`);

382-386: Improve error handling in sequence parsing.

The error handling could be more informative by including the original error message.

-await captureException(
-  e instanceof Error ? e : new Error(String(e))
-)
-this.logger.warn(`error to parse sequence`)
+const error = normalizeError(e);
+await captureException(error);
+this.logger.warn(`Failed to parse sequence: ${error.message}`);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6ab7992 and b4b8739.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • .gitignore (1 hunks)
  • package.json (1 hunks)
  • src/db/controller/packet.ts (2 hunks)
  • src/index.ts (1 hunks)
  • src/lib/error-handlers.ts (1 hunks)
  • src/lib/sentry.ts (1 hunks)
  • src/workers/chain.ts (5 hunks)
  • src/workers/wallet.ts (4 hunks)
🔇 Additional comments (4)
.gitignore (2)

12-13: Clarify the /test_db ignore entry.
The modification from a negative (-/test_db) to a positive (/test_db) entry reaffirms that the test database directory will be ignored. This change maintains security by ensuring that any temporary or test-related data isn’t inadvertently committed. Please double-check that this change does not conflict with any local testing setups where the /test_db folder might be needed.


14-15: Protect Sensitive Data by Ignoring .env* Files.
Adding the .env* entry is a strong move to avoid accidental commits of environment variables, which are especially critical now with the Sentry integration requiring secrets like SENTRY_DSN. This helps keep sensitive configuration secure.

src/lib/sentry.ts (1)

1-4: Imports are clear and well-structured.
No concerns regarding correctness or maintainability in these lines.

src/index.ts (1)

8-11: Good practice of early Sentry initialization.
Calling initSentry before other setup steps ensures errors are tracked from the start. This integration looks solid.

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)
src/workers/wallet.ts (1)

394-400: Enhance error message with transaction context.

The error handling could be improved by including more transaction context in the error message:

 const error = new Error(
-  `Tx failed. raw log - ${result.raw_log}, code - ${result.code}`
+  `Transaction failed. Chain: ${this.chain.chainId}, Address: ${this.address()}, Code: ${result.code}, Raw Log: ${result.raw_log}`
 )

 await captureException(error)
-this.logger.error(error)
+this.logger.error(`Transaction error: ${error.message}`)
 throw error
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b4b8739 and 4286b96.

📒 Files selected for processing (1)
  • src/workers/wallet.ts (3 hunks)

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

♻️ Duplicate comments (1)
src/workers/wallet.ts (1)

47-61: 🛠️ Refactor suggestion

Enhance retry mechanism with exponential backoff.

The current retry implementation with a fixed delay could be improved.

Apply the changes suggested in the previous review to implement exponential backoff for better reliability.

🧹 Nitpick comments (2)
src/workers/wallet.ts (2)

72-79: Consider adding rate limiting to error tracking.

The current implementation tracks errors with a 10-minute cooldown, which is good. However, consider these enhancements:

  1. Make the cooldown duration configurable
  2. Add a maximum error count per error code
+const ERROR_COOLDOWN_MS = 10 * 60 * 1000  // 10 minutes
+const MAX_ERRORS_PER_CODE = 100

 private async checkAndStoreError(code: string, error: Error) {
   const now = Date.now()
   const lastErrorTime = this.errorTracker.get(code) ?? 0
-  if (now - lastErrorTime > 10 * 60 * 1000) {
+  if (now - lastErrorTime > ERROR_COOLDOWN_MS) {
     this.errorTracker.set(code, now)
+    const errorCount = (this.errorTracker.get(`${code}_count`) ?? 0) + 1
+    if (errorCount <= MAX_ERRORS_PER_CODE) {
+      this.errorTracker.set(`${code}_count`, errorCount)
       await captureException(error)
+    }
   }
 }

404-410: Consider categorizing errors by type.

The error handling for transaction failures could be enhanced by categorizing errors and providing more context.

+enum TxErrorCategory {
+  SEQUENCE_MISMATCH = 'sequence_mismatch',
+  INSUFFICIENT_FUNDS = 'insufficient_funds',
+  UNKNOWN = 'unknown'
+}

+private getTxErrorCategory(rawLog: string): TxErrorCategory {
+  if (rawLog.startsWith('account sequence mismatch')) {
+    return TxErrorCategory.SEQUENCE_MISMATCH
+  }
+  if (rawLog.includes('insufficient funds')) {
+    return TxErrorCategory.INSUFFICIENT_FUNDS
+  }
+  return TxErrorCategory.UNKNOWN
+}

-const error = new Error(
-  `Tx failed. raw log - ${result.raw_log}, code - ${result.code}`
-)
+const category = this.getTxErrorCategory(result.raw_log)
+const error = new Error(
+  `Tx failed. Category: ${category}, raw log - ${result.raw_log}, code - ${result.code}`
+)

-await this.checkAndStoreError(result.code.toString(), error)
+await this.checkAndStoreError(`${category}_${result.code}`, error)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4286b96 and 09dfcb9.

📒 Files selected for processing (1)
  • src/workers/wallet.ts (4 hunks)
🔇 Additional comments (1)
src/workers/wallet.ts (1)

24-24: LGTM! Good addition of error tracking capabilities.

The integration of Sentry and the addition of an error tracker map are well-structured additions that will improve error monitoring.

Also applies to: 30-30

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

🧹 Nitpick comments (3)
src/lib/error-handlers.ts (3)

4-15: Consider making the exit delay configurable.

The 1-second delay before process exit is hardcoded. Consider making this configurable to accommodate different environments and network conditions.

+const EXIT_DELAY_MS = process.env.ERROR_HANDLER_EXIT_DELAY_MS 
+  ? parseInt(process.env.ERROR_HANDLER_EXIT_DELAY_MS, 10)
+  : 1000;
+
 export function setupErrorHandlers(): void {
   process.on('unhandledRejection', (error: unknown) => {
     console.error('Unhandled rejection:', error)

     const errorObject =
       error instanceof Error
         ? error
         : new Error(typeof error === 'string' ? error : JSON.stringify(error))

     void captureException(errorObject)

-    setTimeout(() => process.exit(1), 1000)
+    setTimeout(() => process.exit(1), EXIT_DELAY_MS)
   })

17-23: Update the exit delay to use the configurable value.

Apply the same configurable exit delay here for consistency.

   process.on('uncaughtException', (error) => {
     console.error('Uncaught exception:', error)

     void captureException(error)

-    setTimeout(() => process.exit(1), 1000)
+    setTimeout(() => process.exit(1), EXIT_DELAY_MS)
   })

3-24: Consider implementing graceful shutdown.

While the error handling is solid, consider implementing a graceful shutdown strategy:

  1. Clean up resources (close database connections, file handles)
  2. Complete in-flight requests
  3. Stop accepting new requests
  4. Notify load balancers/health checks

This ensures proper cleanup and minimizes impact during error scenarios.

Would you like me to provide an example implementation of a graceful shutdown handler?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 09dfcb9 and cc25576.

📒 Files selected for processing (1)
  • src/lib/error-handlers.ts (1 hunks)
🔇 Additional comments (2)
src/lib/error-handlers.ts (2)

7-11: LGTM! Robust error object handling.

The code properly handles different error types by converting them to Error instances, which is crucial for consistent error reporting in Sentry.


1-3:

✅ Verification successful

Verify the Sentry module implementation.

The code imports captureException from a local Sentry module. Let's verify its implementation to ensure proper error reporting.


🏁 Script executed:

#!/bin/bash
# Description: Verify the Sentry module implementation
# Check if the sentry.ts file exists and contains the captureException implementation
fd -e ts -E "node_modules" "sentry.ts" --exec cat {}

Length of output: 1816


Sentry Module Integration Verified

The captureException implementation in the local Sentry module is correctly configured to report errors:

  • It appropriately checks for the SENTRY_DSN environment variable before attempting reporting.
  • The error is captured within a Sentry scope with the specified severity level.
  • A flush is performed (with a 1-second timeout) to ensure events are sent.

There are no issues with the Sentry integration, and the usage in setupErrorHandlers() aligns with our intended error reporting behavior.

Copy link
Collaborator

@ALPAC-4 ALPAC-4 left a comment

Choose a reason for hiding this comment

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

LGTM

@Benzbeeb Benzbeeb merged commit 516e87a into main Feb 19, 2025
4 checks passed
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