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(cli): add sentry logging #637

Open
wants to merge 2 commits into
base: chore/add-sentry
Choose a base branch
from

Conversation

muntaxir4
Copy link
Contributor

@muntaxir4 muntaxir4 commented Jan 18, 2025

User description

Description

CLI:

  • Add sentry logging
  • Fix get and list commands for secret and variable.

Fixes #529

Developer's checklist

  • My PR follows the style guidelines of this project
  • I have performed a self-check on my work

If changes are made in the code:

  • I have followed the coding guidelines
  • My changes in code generate no new warnings
  • My changes are breaking another fix/feature of the project
  • I have added test cases to show that my feature works
  • I have added relevant screenshots in my PR
  • There are no UI/UX issues

Documentation Update

  • This PR requires an update to the documentation at docs.keyshade.xyz
  • I have made the necessary updates to the documentation, or no documentation changes are required.

PR Type

Enhancement, Bug fix, Documentation, Other


Description

  • Integrated Sentry logging and error monitoring across CLI, platform, and API.

  • Added new commands and improved existing ones in CLI for secrets and variables management.

  • Enhanced error handling and logging with Sentry integration in CLI and platform.

  • Updated environment schemas and configurations to support Sentry.

  • Added example pages, API routes, and utilities for testing Sentry integration.

  • Updated documentation and example environment files with Sentry configurations.

  • Refactored and improved application setup, logging, and instrumentation for better error tracking.

  • Updated dependencies and build configurations to include Sentry-related packages.

  • Added Sentry release management to CI workflow.


Changes walkthrough 📝

Relevant files
Enhancement
12 files
page.tsx
Add Sentry example page for testing integration.                 

apps/platform/src/app/sentry-example-page/page.tsx

  • Added a new page to test Sentry integration in the platform.
  • Includes a button to trigger a sample error and links to Sentry
    documentation.
  • Utilizes Sentry's startSpan for error monitoring.
  • +85/-0   
    main.ts
    Refactor Sentry initialization and app setup.                       

    apps/api/src/main.ts

  • Refactored Sentry initialization logic with updated environment
    variables.
  • Added support for DOMAIN and isHttp in application setup.
  • Improved logging for Sentry initialization and application startup.
  • +17/-20 
    get.secret.ts
    Update `get` command for secrets with environment support.

    apps/cli/src/commands/secret/get.secret.ts

  • Updated get command to include environment slug as an argument.
  • Removed decryption option and adjusted logic for fetching secrets.
  • Enhanced error handling and logging for secret retrieval.
  • +19/-34 
    list.secret.ts
    Enhance `list` command for secrets with decryption.           

    apps/cli/src/commands/secret/list.secret.ts

  • Added decryption option to the list command for secrets.
  • Improved error handling and logging for secret listing.
  • Adjusted command description for clarity.
  • +35/-6   
    get.variable.ts
    Add `get` command for variables with environment support.

    apps/cli/src/commands/variable/get.variable.ts

  • Introduced a new get command for variables under a project and
    environment.
  • Added logic for fetching and displaying variables.
  • Included error handling and metrics reporting.
  • +70/-0   
    base.command.ts
    Add Sentry integration to base command logic.                       

    apps/cli/src/commands/base.command.ts

  • Integrated Sentry instance initialization for metrics-enabled
    commands.
  • Enhanced error reporting with Sentry in the base command logic.
  • +8/-2     
    sentry.ts
    Introduce Sentry utility for CLI error reporting.               

    apps/cli/src/util/sentry.ts

  • Added a utility class for Sentry integration in CLI.
  • Configured Sentry with profiling and error reporting capabilities.
  • Included a method for capturing exceptions.
  • +41/-0   
    global-error.tsx
    Add global error handling with Sentry integration.             

    apps/platform/src/app/global-error.tsx

  • Added a global error component for handling uncaught errors in the
    platform.
  • Integrated Sentry for capturing exceptions.
  • Utilized Next.js default error page for rendering.
  • +27/-0   
    variable.command.ts
    Register `get` command for variables in CLI.                         

    apps/cli/src/commands/variable.command.ts

    • Registered the new get command for variables in the CLI.
    +3/-1     
    logger.ts
    Enhance logger with Sentry error reporting.                           

    apps/cli/src/util/logger.ts

  • Added a report method to log errors to Sentry.
  • Integrated Sentry into the existing logging utility.
  • +5/-0     
    instrumentation.ts
    Add Sentry instrumentation for platform.                                 

    apps/platform/src/instrumentation.ts

  • Added instrumentation logic for Sentry in the platform.
  • Configured Sentry for different runtime environments.
  • +13/-0   
    route.ts
    Add Sentry example API route for testing.                               

    apps/platform/src/app/api/sentry-example-api/route.ts

  • Added a faulty API route to test Sentry error monitoring.
  • Throws a sample error for testing purposes.
  • +9/-0     
    Configuration changes
    9 files
    env.schema.ts
    Update environment schema with Sentry and defaults.           

    apps/api/src/common/env/env.schema.ts

  • Updated environment schema to include default values for API_PORT and
    DOMAIN.
  • Renamed Sentry-related environment variables for better clarity.
  • Adjusted sample rate schemas for Sentry API.
  • +26/-14 
    env.ts
    Add Sentry environment variables for platform.                     

    apps/platform/src/env.ts

  • Added optional Sentry-related environment variables for the platform.
  • Updated schema to include profiling and tracing sample rates.
  • +4/-1     
    sentry.client.config.ts
    Add Sentry client configuration for platform.                       

    apps/platform/sentry.client.config.ts

  • Added Sentry client configuration for the platform.
  • Configured DSN, sample rates, and debugging options.
  • +9/-0     
    sentry.edge.config.ts
    Add Sentry edge configuration for platform.                           

    apps/platform/sentry.edge.config.ts

  • Added Sentry edge configuration for the platform.
  • Configured DSN, sample rates, and debugging options.
  • +9/-0     
    sentry.server.config.ts
    Add Sentry server configuration for platform.                       

    apps/platform/sentry.server.config.ts

  • Added Sentry server configuration for the platform.
  • Configured DSN, sample rates, and debugging options.
  • +9/-0     
    index.ts
    Add dotenv configuration to CLI entry point.                         

    apps/cli/src/index.ts

    • Added dotenv configuration for loading environment variables.
    +1/-0     
    next.config.js
    Integrate Sentry into Next.js configuration.                         

    apps/platform/next.config.js

  • Integrated Sentry configuration into the Next.js build process.
  • Added options for source map uploads and React component annotations.
  • +52/-8   
    esbuild.config.js
    Add esbuild configuration for CLI with Sentry.                     

    apps/cli/esbuild.config.js

  • Added esbuild configuration for building the CLI with Sentry
    integration.
  • Configured environment variables for Sentry.
  • +19/-0   
    release.yml
    Add Sentry release management to CI workflow.                       

    .github/workflows/release.yml

  • Added a new workflow step for Sentry release management.
  • Configured Sentry CLI for release creation and deployment.
  • +37/-1   
    Error handling
    1 files
    create.environment.ts
    Enhance error reporting for environment creation.               

    apps/cli/src/commands/environment/create.environment.ts

  • Added metrics-enabled error reporting for environment creation
    failures.
  • Improved logging for error scenarios.
  • +4/-0     
    Documentation
    2 files
    .env.example
    Update example environment variables with Sentry settings.

    .env.example

  • Updated example environment variables to include Sentry
    configurations.
  • Added placeholders for DSN and sample rates.
  • +22/-12 
    .env.example
    Add example environment file for CLI.                                       

    apps/cli/.env.example

  • Added an example environment file for CLI with Sentry DSN placeholder.
  • +1/-0     
    Dependencies
    3 files
    package.json
    Update CLI package.json with Sentry dependencies.               

    apps/cli/package.json

  • Updated build script to use esbuild configuration.
  • Added Sentry-related dependencies and sourcemap upload script.
  • +6/-2     
    package.json
    Update platform package.json with Sentry dependency.         

    apps/platform/package.json

  • Updated package name to include namespace.
  • Added Sentry dependency for platform.
  • +2/-1     
    package-lock.json
    Added Sentry dependencies and updated package metadata.   

    apps/cli/package-lock.json

  • Added new dependencies related to Sentry, including
    @sentry/esbuild-plugin, @sentry/node, and @sentry/profiling-node.
  • Introduced numerous new packages and sub-dependencies to support
    Sentry integration and other functionalities.
  • Removed dev flags from some existing dependencies, indicating they are
    now required in production.
  • Updated or added metadata for various dependencies, such as licenses,
    engines, and funding information.
  • +1246/-12
    Miscellaneous
    2 files
    package.json
    Update API package.json with namespace.                                   

    apps/api/package.json

    • Updated package name to include namespace.
    +1/-1     
    package.json
    Update web package.json with namespace.                                   

    apps/web/package.json

    • Updated package name to include namespace.
    +1/-1     
    Additional files
    55 files
    deploy-api.yml +13/-2   
    Dockerfile +0/-1     
    package-lock.json +2/-2     
    webpack.config.js +0/-24   
    delete.environment.ts +3/-0     
    get.environment.ts +3/-0     
    list.environment.ts +3/-0     
    update.environment.ts +3/-0     
    create.project.ts +3/-0     
    delete.project.ts +3/-0     
    fork.project.ts +3/-0     
    get.project.ts +3/-0     
    import.project.ts +0/-1     
    list-forks.project.ts +5/-0     
    list.project.ts +3/-0     
    sync.project.ts +3/-0     
    unlink.project.ts +3/-0     
    update.project.ts +3/-0     
    create.secret.ts +3/-0     
    delete.secret.ts +3/-0     
    revisions.secret.ts +3/-0     
    rollback.secret.ts +4/-1     
    update.secret.ts +3/-0     
    create.variable.ts +3/-0     
    delete.variable.ts +3/-0     
    list.variable.ts +5/-0     
    revisions.variable.ts +5/-0     
    rollback.variable.ts +3/-0     
    update.variable.ts +3/-0     
    create.workspace.ts +3/-0     
    delete.workspace.ts +3/-0     
    export.workspace.ts +3/-0     
    get.workspace.ts +3/-0     
    list.workspace.ts +3/-0     
    accept-invitation.membership.ts +3/-0     
    cancel-invitation.membership.ts +3/-0     
    decline-invitation.membership.ts +3/-0     
    get-all-members.membership.ts +3/-0     
    invite.membership.ts +3/-0     
    leave.membership.ts +3/-0     
    remove.membership.ts +3/-0     
    transfer-ownership.membership copy.ts +3/-0     
    update-role.membership.ts +3/-0     
    create.role.ts +5/-0     
    delete.role.ts +5/-0     
    get.role.ts +5/-0     
    list.role.ts +5/-0     
    update.role.ts +5/-0     
    search.workspace.ts +5/-0     
    update.workspace.ts +3/-0     
    configuration.ts +1/-0     
    tsconfig.json +2/-1     
    package.json +30/-27 
    pnpm-lock.yaml +1112/-64
    turbo.json +3/-1     

    Need help?
  • Type /help how to ... in the comments thread for any question about Qodo Merge usage.
  • Check out the documentation for more information.
  • @muntaxir4 muntaxir4 changed the base branch from develop to chore/add-sentry January 18, 2025 20:41
    Copy link
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    🎫 Ticket compliance analysis ✅

    529 - Fully compliant

    Compliant requirements:

    • Added Sentry error reporting when metrics_enabled is true
    • Errors sent to Sentry for internal errors and 500 API responses
    • Added Logger.report function that logs and sends to Sentry
    • Environment set as 'CLI'
    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling

    The Sentry initialization could fail silently if DSN is missing. Consider adding explicit validation and error handling.

      try {
        Sentry.init({
          dsn: process.env.SENTRY_DSN,
          tracesSampleRate: 1.0,
          environment: 'CLI',
          integrations: [nodeProfilingIntegration()],
          beforeSend(event) {
            if (event.exception) {
              Logger.log(
                'A detailed error report has been sent to the Keyshade team.'
              )
            }
            return event
          }
        })
        return Sentry
      } catch (error) {
        Logger.error('Failed to initialize error reporting.')
        Sentry.captureException(error)
        return null
      }
    }
    Error Recovery

    Error handling in action() method swallows errors without proper recovery or exit codes, which could leave CLI in inconsistent state.

    } catch (error) {
      const errorInfo = error as string
      Logger.error(errorInfo)
      if (this.metricsEnabled) Logger.report(errorInfo)
    }

    Copy link
    Contributor

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Possible issue
    Ensure the correct directory path is used when creating parent directories for configuration files

    The ensureDirectoryExists function should be called with the directory path, not the
    file path. Extract the directory path using dirname to ensure the parent directory
    exists before creating the file.

    apps/cli/src/util/configuration.ts [32-34]

     if (!existsSync(path)) {
    -  await ensureDirectoryExists(path)
    +  await ensureDirectoryExists(dirname(path))
       await writeFile(path, '{}', 'utf8')
     }
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: This is a critical bug fix. Using the file path instead of directory path with ensureDirectoryExists could cause file creation failures, as the parent directory must exist before creating a file.

    9
    Add proper error handling for network requests to prevent unhandled promise rejections

    Add error handling for the fetch request to prevent unhandled promise rejections.
    Wrap the fetch call in a try-catch block and handle network errors explicitly.

    apps/platform/src/app/sentry-example-page/page.tsx [52-63]

     await Sentry.startSpan(
       {
         name: 'Example Frontend Span',
         op: 'test'
       },
       async () => {
    -    const res = await fetch('/api/sentry-example-api')
    -    if (!res.ok) {
    -      throw new Error('Sentry Example Frontend Error')
    +    try {
    +      const res = await fetch('/api/sentry-example-api')
    +      if (!res.ok) {
    +        throw new Error('Sentry Example Frontend Error')
    +      }
    +    } catch (error) {
    +      Sentry.captureException(error)
    +      throw error
         }
       }
     )
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: The suggestion adds important error handling for network requests, capturing and properly handling fetch errors with Sentry. This improves error tracking and prevents unhandled promise rejections in production.

    8
    Security
    Implement safe error object serialization to prevent exposure of sensitive data and handle circular references

    Avoid directly stringifying the error object as it may contain sensitive information
    or circular references. Instead, extract and log only necessary error properties
    like statusCode, name, and message.

    apps/cli/src/commands/workspace/membership/update-role.membership.ts [76-78]

     if (this.metricsEnabled && error?.statusCode === 500) {
    -  Logger.report('Failed to update roles.\n' + JSON.stringify(error))
    +  Logger.report('Failed to update roles.\n' + JSON.stringify({
    +    statusCode: error.statusCode,
    +    message: error.message,
    +    name: error.name
    +  }))
     }
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: This is an important security enhancement that prevents potential exposure of sensitive information and handles JSON serialization issues with circular references in error objects.

    8
    General
    Remove unreachable code that follows a throw statement

    The unreachable code after throwing an error should be removed as it will never be
    executed.

    apps/platform/src/app/api/sentry-example-api/route.ts [6-8]

     export function GET() {
       throw new Error('Sentry Example API Route Error')
    -  return NextResponse.json({ data: 'Testing Sentry Error...' })
     }
    • Apply this suggestion
    Suggestion importance[1-10]: 5

    Why: The suggestion removes dead code that can never be executed after the throw statement. While this is a valid improvement for code cleanliness, it's a relatively minor issue since the code would never execute anyway.

    5

    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.

    CLI: Add support for sentry
    1 participant