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: otel support #2236

Open
wants to merge 14 commits into
base: dev
Choose a base branch
from
Open

feat: otel support #2236

wants to merge 14 commits into from

Conversation

liorzam
Copy link
Collaborator

@liorzam liorzam commented Mar 21, 2024

User description

Description

Elaborate on the subject, motivation, and context.

image

Related issues

  • Provide a link to each related issue.

Breaking changes

  • Describe the breaking changes that this pull request introduces.

How these changes were tested

  • Describe the tests that you ran to verify your changes, including devices, operating systems, browsers and versions.

Examples and references

  • Links, screenshots, and other resources related to this change.

Checklist

  • [] I have read the contribution guidelines of this project
  • [] I have read the style guidelines of this project
  • [] I have performed a self-review of my own code
  • [] I have commented my code, particularly in hard-to-understand areas
  • [] I have made corresponding changes to the documentation
  • [] My changes generate no new warnings and errors
  • [] New and existing tests pass locally with my changes

Type

enhancement


Description

  • Integrated OpenTelemetry for tracing across various services including HTTP, Winston, NestJS, AWS SDK, Prisma, and Express.
  • Configured OTLPTraceExporter and resource detectors for enhanced observability.
  • Modified request ID middleware and Sentry service to utilize OpenTelemetry trace IDs.
  • Added necessary OpenTelemetry dependencies and configured Docker Compose for Jaeger tracing environment.
  • Enabled tracing preview feature in Prisma schema for database query tracing.

Changes walkthrough

Relevant files
Enhancement
tracer.ts
Integrate OpenTelemetry Tracing with OTLP Exporter             

services/workflows-service/src/traces/tracer.ts

  • Introduced OpenTelemetry tracing with OTLPTraceExporter configuration.
  • Configured resource detectors, span processors, and instrumentations
    for various services including HTTP, Winston, NestJS, AWS SDK, Prisma,
    and Express.
  • Implemented graceful shutdown for the tracing SDK.
  • +66/-0   
    request-id.middleware.ts
    Use OpenTelemetry Trace ID in Request ID Middleware           

    services/workflows-service/src/common/middlewares/request-id.middleware.ts

  • Imported trace and context from OpenTelemetry API.
  • Replaced setReqId with setTraceId to use trace ID from OpenTelemetry
    spans.
  • +14/-5   
    sentry.service.ts
    Enhance Sentry Integration with OpenTelemetry Trace ID     

    services/workflows-service/src/sentry/sentry.service.ts

  • Imported OpenTelemetry API for tracing.
  • Modified Sentry to use OpenTelemetry trace ID for better error
    tracking.
  • +8/-1     
    app-logger.service.ts
    Simplify Log Metadata Retrieval                                                   

    services/workflows-service/src/common/app-logger/app-logger.service.ts

    • Simplified getLogMetadata method by removing redundant code.
    +1/-9     
    main.ts
    Initialize OpenTelemetry Tracing on Startup                           

    services/workflows-service/src/main.ts

    • Added startup sequence for OpenTelemetry tracing SDK.
    +4/-0     
    schema.prisma
    Enable Tracing Feature in Prisma Schema                                   

    services/workflows-service/prisma/schema.prisma

    • Enabled tracing preview feature in Prisma client generator.
    +1/-0     
    Dependencies
    package.json
    Add OpenTelemetry Dependencies for Tracing                             

    services/workflows-service/package.json

  • Added multiple OpenTelemetry related packages for tracing and
    instrumentation.
  • Adjusted package order for consistency.
  • +21/-5   
    Configuration changes
    docker-compose.otel.yml
    Setup Docker Compose for Jaeger Tracing Environment           

    services/workflows-service/docker-compose.otel.yml

  • Created a new Docker Compose file for setting up a tracing environment
    with Jaeger.

  • PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Summary by CodeRabbit

    • New Features

      • Introduced distributed tracing support using OpenTelemetry, enhancing monitoring and observability.
      • Added Docker Compose configuration for setting up Jaeger tracing service.
    • Improvements

      • Updated dependencies to include OpenTelemetry and Prisma for better tracing and instrumentation.
    • Bug Fixes

      • Simplified logging metadata retrieval in AppLoggerService for more efficient log handling.
    • Enhancements

      • Enhanced Sentry integration to include trace IDs for improved error tracking and diagnostics.
      • Introduced custom HTTP instrumentation for better tracing of HTTP requests.

    Copy link

    changeset-bot bot commented Mar 21, 2024

    ⚠️ No Changeset found

    Latest commit: 8738727

    Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

    This PR includes no changesets

    When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

    Click here to learn what changesets are, and how to add one.

    Click here if you're a maintainer who wants to add a changeset to this PR

    Copy link
    Contributor

    coderabbitai bot commented Mar 21, 2024

    Walkthrough

    The changes introduce OpenTelemetry-based tracing to the workflows service, enhancing observability by integrating Jaeger for distributed tracing. Key updates include setting up tracing in the Prisma schema, initializing tracing in the main application, and configuring Docker Compose for Jaeger. Additionally, the AppLoggerService and SentryService have been updated to support tracing metadata, and custom HTTP instrumentation has been added.

    Changes

    File Path Change Summary
    services/workflows-service/prisma/schema.prisma Added previewFeatures with ["tracing"] to the generator client block.
    services/workflows-service/src/main.ts Imported tracingSdk and started tracing before ts-reset.
    services/workflows-service/docker-compose.otel.yml Introduced Docker Compose configuration for Jaeger tracing service.
    services/workflows-service/src/traces/tracer.ts Added tracing setup using OpenTelemetry, including exporters, propagators, and instrumentations.
    services/workflows-service/package.json Added dependencies for OpenTelemetry and Prisma instrumentation.
    services/workflows-service/prisma/data-migrations Updated subproject commit reference.
    services/workflows-service/src/common/app-logger/app-logger.service.ts Simplified getLogMetadata method by removing reqId handling.
    services/workflows-service/src/sentry/sentry.service.ts Modified _setExtraData method to include traceId in Sentry scope.
    services/workflows-service/src/traces/http-intrumentation.ts Introduced custom BallerineHttpInstrumentation for HTTP tracing with URL filters.

    Sequence Diagram(s) (Beta)

    sequenceDiagram
        participant User
        participant Service
        participant TracingSDK
        participant Jaeger
        participant Sentry
    
        User->>Service: Send Request
        activate Service
        Service->>TracingSDK: Start Trace
        activate TracingSDK
        TracingSDK->>Jaeger: Export Trace Data
        deactivate TracingSDK
        Service->>Sentry: Log with TraceID
        deactivate Service
        Sentry->>Jaeger: Correlate TraceID
    

    Poem

    In the land of code where data flows,
    Traces now bloom where Jaeger grows.
    With OpenTelemetry's gentle embrace,
    Every request finds its place.
    Logs and spans in harmony sing,
    A clearer view, observability's spring.
    🐇✨


    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>.
      • 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 generate interesting stats about this repository and render them as a table.
      • @coderabbitai show all the console.log statements in this repository.
      • @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 as 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 resolve resolve all the CodeRabbit review comments.
    • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
    • @coderabbitai help to get help.

    Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

    CodeRabbit Configration 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.

    @github-actions github-actions bot added the enhancement New feature or request label Mar 21, 2024
    Copy link
    Contributor

    PR Description updated to latest commit (bd87c13)

    Copy link
    Contributor

    PR Review

    ⏱️ Estimated effort to review [1-5]

    4, due to the integration of a new tracing system across multiple services and dependencies, which requires a thorough understanding of OpenTelemetry, its instrumentation, and how it interacts with existing services. The changes span across multiple files and include both configuration and code changes, making the review process more involved.

    🧪 Relevant tests

    No

    🔍 Possible issues

    Possible Performance Concern: The use of SimpleSpanProcessor alongside BatchSpanProcessor in tracer.ts might lead to performance issues in production. SimpleSpanProcessor is generally recommended for debugging purposes only.

    Potential Error Handling Issue: In request-id.middleware.ts, there's a catch block that logs an error if setting the traceId fails, but it doesn't rethrow the error or handle it further. This might suppress important errors that should be addressed.

    Logging Inconsistency: The removal of reqId from getLogMetadata in app-logger.service.ts without replacing it with traceId might lead to less informative logs, as there's no longer a request or trace identifier included.

    🔒 Security concerns

    No

    Code feedback:
    relevant fileservices/workflows-service/src/traces/tracer.ts
    suggestion      

    Consider removing SimpleSpanProcessor or using it conditionally for non-production environments to avoid potential performance issues. [important]

    relevant linenew opentelemetry.tracing.SimpleSpanProcessor(new opentelemetry.tracing.ConsoleSpanExporter()),

    relevant fileservices/workflows-service/src/common/middlewares/request-id.middleware.ts
    suggestion      

    Ensure error handling in setTraceId method is robust, possibly by rethrowing the error or implementing additional error handling logic. [important]

    relevant linethis.logger.error('traceId is undefined');

    relevant fileservices/workflows-service/src/common/app-logger/app-logger.service.ts
    suggestion      

    Reinstate logging of request or trace identifiers by adding traceId to getLogMetadata for improved log traceability. [medium]

    relevant lineconst metadata = {};

    relevant fileservices/workflows-service/src/sentry/sentry.service.ts
    suggestion      

    Consider adding a fallback mechanism for traceId in _setExtraData to ensure Sentry always receives some form of identifier, enhancing error tracking. [medium]

    relevant linetraceId = activeSpan?.spanContext().traceId;


    ✨ Review tool usage guide:

    Overview:
    The review tool scans the PR code changes, and generates a PR review. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.
    When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:

    /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
    

    With a configuration file, use the following template:

    [pr_reviewer]
    some_config1=...
    some_config2=...
    
    Utilizing extra instructions

    The review tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize.

    Examples for extra instructions:

    [pr_reviewer] # /review #
    extra_instructions="""
    In the 'possible issues' section, emphasize the following:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    How to enable\disable automation
    • When you first install PR-Agent app, the default mode for the review tool is:
    pr_commands = ["/review", ...]
    

    meaning the review tool will run automatically on every PR, with the default configuration.
    Edit this field to enable/disable the tool, or to change the used configurations

    Auto-labels

    The review tool can auto-generate two specific types of labels for a PR:

    • a possible security issue label, that detects possible security issues (enable_review_labels_security flag)
    • a Review effort [1-5]: x label, where x is the estimated effort to review the PR (enable_review_labels_effort flag)
    Extra sub-tools

    The review tool provides a collection of possible feedbacks about a PR.
    It is recommended to review the possible options, and choose the ones relevant for your use case.
    Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example:
    require_score_review, require_soc2_ticket, require_can_be_split_review, and more.

    Auto-approve PRs

    By invoking:

    /review auto_approve
    

    The tool will automatically approve the PR, and add a comment with the approval.

    To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following:

    [pr_reviewer]
    enable_auto_approval = true
    

    (this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository)

    You can also enable auto-approval only if the PR meets certain requirements, such as that the estimated_review_effort is equal or below a certain threshold, by adjusting the flag:

    [pr_reviewer]
    maximal_review_effort = 5
    
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the review usage page for a comprehensive guide on using this tool.

    Copy link
    Contributor

    github-actions bot commented Mar 21, 2024

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Enhancement
    Initialize the metadata object with default values.

    Consider initializing metadata with relevant default values or properties that might be
    universally required, similar to the previous implementation that included reqId. This
    ensures that the metadata object is always in a predictable state.

    services/workflows-service/src/common/app-logger/app-logger.service.ts [41]

    -const metadata = {};
    +const metadata = {
    +  traceId: undefined, // or any other default properties
    +};
     
    Log error messages for better debugging.

    To improve error handling and debugging, consider logging the error message when catching
    exceptions in setTraceId. This provides more context about the error, making it easier to
    diagnose issues.

    services/workflows-service/src/common/middlewares/request-id.middleware.ts [83-84]

     } catch (e) {
    -  this.logger.error('Could not set requestId');
    +  this.logger.error(`Could not set requestId: ${e.message}`);
     
    Best practice
    Use environment variables for configuration values.

    Consider using environment variables for configuration values such as the
    OTLPTraceExporter URL. This makes the application more flexible and secure, as it allows
    for different configurations across environments without changing the code.

    services/workflows-service/src/traces/tracer.ts [22]

    -url: 'http://localhost:4318/v1/traces',
    +url: process.env.OTLP_TRACE_EXPORTER_URL || 'http://localhost:4318/v1/traces',
     
    Use a logging framework instead of console for process event handlers.

    Instead of directly using console.log and console.error for logging within the
    process.on('SIGTERM', ...) handler, consider using a more robust logging framework or the
    application's logger service. This approach allows for more consistent and configurable
    logging behavior across the application.

    services/workflows-service/src/traces/tracer.ts [64-65]

    -.then(() => console.log('Tracing terminated'))
    -.catch((error: unknown) => console.error('Error terminating tracing', error));
    +.then(() => this.logger.info('Tracing terminated'))
    +.catch((error: unknown) => this.logger.error('Error terminating tracing', error));
     
    Maintainability
    Refactor traceId fetching into a separate method for clarity.

    To ensure that the traceId is always set in Sentry's scope, consider moving the logic of
    fetching the traceId from the active span into a separate method. This improves code
    readability and maintainability.

    services/workflows-service/src/sentry/sentry.service.ts [43-46]

    -let traceId = this.cls.get('traceId');
    -if (!traceId) {
    -  const activeSpan = api.trace.getSpan(api.context.active());
    -  traceId = activeSpan?.spanContext().traceId;
    +let traceId = this.getTraceId();
    +...
    +private getTraceId(): string | undefined {
    +  let traceId = this.cls.get('traceId');
    +  if (!traceId) {
    +    const activeSpan = api.trace.getSpan(api.context.active());
    +    traceId = activeSpan?.spanContext().traceId;
    +  }
    +  return traceId;
     }
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.
    When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:

    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    

    With a configuration file, use the following template:

    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    
    Enabling\disabling automation

    When you first install the app, the default mode for the improve tool is:

    pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...]
    

    meaning the improve tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.

    Utilizing extra instructions

    Extra instructions are very important for the improve tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on.

    Examples for extra instructions:

    [pr_code_suggestions] # /improve #
    extra_instructions="""
    Emphasize the following aspects:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    A note on code suggestions quality
    • While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically.
    • Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base.
    • Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the custom suggestions 💎 tool
    • With large PRs, best quality will be obtained by using 'improve --extended' mode.
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the improve usage page for a more comprehensive guide on using this tool.

    Copy link
    Contributor

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

    Review Status

    Actionable comments generated: 0

    Configuration used: CodeRabbit UI

    Commits Files that changed from the base of the PR and between 9f76d65 and bd87c13.
    Files ignored due to path filters (3)
    • pnpm-lock.yaml is excluded by: !**/*.yaml
    • services/workflows-service/docker-compose.otel.yml is excluded by: !**/*.yml
    • services/workflows-service/package.json is excluded by: !**/*.json
    Files selected for processing (7)
    • services/workflows-service/prisma/data-migrations (1 hunks)
    • services/workflows-service/prisma/schema.prisma (1 hunks)
    • services/workflows-service/src/common/app-logger/app-logger.service.ts (1 hunks)
    • services/workflows-service/src/common/middlewares/request-id.middleware.ts (3 hunks)
    • services/workflows-service/src/main.ts (1 hunks)
    • services/workflows-service/src/sentry/sentry.service.ts (2 hunks)
    • services/workflows-service/src/traces/tracer.ts (1 hunks)
    Additional comments: 7
    services/workflows-service/prisma/data-migrations (1)
    • 1-1: The update to the subproject commit reference is noted. Ensure that the new commit (b0c26b898feb0705286b4d7f0266bcd740062ee6) has been thoroughly tested for stability and compatibility with the main project.
    services/workflows-service/src/common/app-logger/app-logger.service.ts (1)
    • 41-41: The simplification of the getLogMetadata method in the AppLoggerService class is noted. Ensure that the simplification has not removed any necessary functionality or error handling that might be required for correct operation.
    services/workflows-service/src/sentry/sentry.service.ts (1)
    • 43-49: The addition of logic to retrieve and set traceId in the SentryService class using OpenTelemetry API is a good enhancement for observability. Ensure that the security implications of exposing trace IDs have been considered and mitigated.
    services/workflows-service/src/traces/tracer.ts (1)
    • 20-66: The setup of OpenTelemetry tracing in the tracer.ts file is comprehensive and well-structured. Ensure that the performance implications of the tracing configuration, especially the batch span processor settings, have been reviewed and optimized for the application's needs.
    services/workflows-service/src/common/middlewares/request-id.middleware.ts (1)
    • 69-81: The updates to use OpenTelemetry trace IDs in the RequestIdMiddleware class, including setting the X-Request-ID header and adding error logging for undefined trace IDs, align well with the goal of enhancing observability. Ensure that the error handling for undefined trace IDs is robust and that any potential security implications of exposing trace IDs are considered.
    services/workflows-service/src/main.ts (1)
    • 1-4: Starting the OpenTelemetry tracing SDK before other imports in main.ts is a good practice for ensuring comprehensive tracing coverage. Ensure that this change does not introduce any unintended side effects, especially in terms of the order of imports and initialization.
    services/workflows-service/prisma/schema.prisma (1)
    • 8-8: Enabling the tracing preview feature in the Prisma client generator configuration is a positive step towards enhancing observability. Ensure that the stability and compatibility of this feature have been thoroughly tested with the project's requirements.

    Copy link
    Contributor

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

    Review Status

    Actionable comments generated: 0

    Configuration used: CodeRabbit UI

    Commits Files that changed from the base of the PR and between bd87c13 and 1f6c4f6.
    Files selected for processing (1)
    • services/workflows-service/src/sentry/sentry.service.ts (2 hunks)
    Files skipped from review as they are similar to previous changes (1)
    • services/workflows-service/src/sentry/sentry.service.ts

    Copy link
    Contributor

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

    Configuration used: CodeRabbit UI

    Commits Files that changed from the base of the PR and between 1f6c4f6 and b32fa45.
    Files ignored due to path filters (1)
    • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
    Files selected for processing (2)
    • services/workflows-service/prisma/schema.prisma (1 hunks)
    • services/workflows-service/src/main.ts (1 hunks)
    Files skipped from review due to trivial changes (1)
    • services/workflows-service/prisma/schema.prisma
    Additional Context Used

    services/workflows-service/src/main.ts Show resolved Hide resolved
    Copy link
    Contributor

    @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

    Review Status

    Configuration used: CodeRabbit UI

    Commits Files that changed from the base of the PR and between b32fa45 and 8db8fa6.
    Files selected for processing (1)
    • services/workflows-service/docker-compose.otel.yml (1 hunks)
    Additional Context Used
    Additional comments not posted (1)
    services/workflows-service/docker-compose.otel.yml (1)

    1-15: The Docker Compose configuration for the Jaeger tracing service is well-defined, with a specific version of the Jaeger image being used (jaegertracing/all-in-one:1.55) and a comprehensive set of ports exposed for its operation. This setup aligns with the objective of enhancing observability through OpenTelemetry integration for development purposes. The use of a specific version addresses previous concerns about stability and consistency with the production environment.

    Copy link
    Contributor

    @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

    Review Status

    Configuration used: CodeRabbit UI

    Commits Files that changed from the base of the PR and between 8db8fa6 and 20bc3e9.
    Files selected for processing (1)
    • services/workflows-service/src/traces/tracer.ts (1 hunks)
    Additional Context Used
    Additional comments not posted (2)
    services/workflows-service/src/traces/tracer.ts (2)

    22-24: The getTracer function is correctly implemented to retrieve the default tracer. This is a straightforward and standard approach in OpenTelemetry SDK usage.


    26-55: The tracing SDK setup includes a comprehensive configuration that covers exporter, propagator, resource detectors, resources, span processors, and instrumentations. A few points to consider:

    • Ensure that the B3Propagator aligns with the tracing system and infrastructure used in the rest of your environment.
    • The use of dockerCGroupV1Detector as a resource detector is a good practice for containerized environments. Verify that it aligns with your deployment strategy.
    • The SimpleSpanProcessor with a ConsoleSpanExporter might be useful for debugging but consider removing or disabling it in production environments to avoid performance impacts.
    • The requestHook in ExpressInstrumentation for capturing request headers can potentially capture sensitive information. Ensure that this does not violate privacy policies or security guidelines.

    Copy link
    Contributor

    @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

    Review Details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits Files that changed from the base of the PR and between 20bc3e9 and 3c1d79f.
    Files ignored due to path filters (1)
    • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
    Files selected for processing (4)
    • services/workflows-service/package.json (1 hunks)
    • services/workflows-service/prisma/data-migrations (1 hunks)
    • services/workflows-service/prisma/schema.prisma (1 hunks)
    • services/workflows-service/src/common/app-logger/app-logger.service.ts (1 hunks)
    Files skipped from review due to trivial changes (3)
    • services/workflows-service/prisma/data-migrations
    • services/workflows-service/prisma/schema.prisma
    • services/workflows-service/src/common/app-logger/app-logger.service.ts
    Additional comments not posted (16)
    services/workflows-service/package.json (16)

    63-63: Ensure compatibility of @opentelemetry/api with other OpenTelemetry packages.


    64-64: Check if @opentelemetry/auto-instrumentations-node is the latest stable version and compatible with the Node.js version used in the project.


    65-65: Confirm that @opentelemetry/exporter-jaeger integrates smoothly with the Jaeger setup specified in the Docker Compose file.


    66-66: Validate the version and configuration of @opentelemetry/exporter-trace-otlp-http to ensure it meets the project's requirements.


    67-67: Ensure that @opentelemetry/exporter-trace-otlp-proto is configured correctly and compatible with the project's tracing infrastructure.

    Verification successful

    The verification process has successfully located the tracing configuration file and confirmed the use of the OTLP exporter within the project's tracing infrastructure. Here are the details:

    • The tracing configuration is managed in the file services/workflows-service/src/traces/tracer.ts.
    • This file includes the import and instantiation of OTLPTraceExporter from the @opentelemetry/exporter-trace-otlp-http package.

    Given this information, it appears that the project is indeed configured to use an OTLP exporter, specifically the HTTP variant, which is compatible with the @opentelemetry/exporter-trace-otlp-proto package mentioned in the review comment.

    • File: services/workflows-service/src/traces/tracer.ts
      • Import statement: import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
      • Usage: const traceExporter = new OTLPTraceExporter();
    Scripts Executed

    The following scripts were executed for the analysis:


    Script:

    #!/bin/bash
    # Description: Verify the configuration and compatibility of the OTLP Proto exporter.
    
    # Test: Check the configuration in the tracing setup.
    grep 'OTLPProtoExporter' src/traces/tracer.ts
    

    Length of output: 99



    Script:

    #!/bin/bash
    # Description: Locate the correct tracing configuration file and verify OTLP exporter configuration.
    
    # Find files related to tracing configuration
    echo "Searching for tracing configuration files:"
    fd --type f "tracer" src
    
    # Check for mentions of OTLP in the codebase
    echo "Searching for mentions of OTLP in the codebase:"
    rg "OTLP" src
    

    Length of output: 373



    Script:

    #!/bin/bash
    # Description: Broad search for tracing configuration files and mentions of OTLP in the entire repository.
    
    # Find files related to tracing configuration in the entire repository
    echo "Searching for tracing configuration files in the entire repository:"
    fd --type f "tracer"
    
    # Check for mentions of OTLP in the entire repository
    echo "Searching for mentions of OTLP in the entire repository:"
    rg "OTLP"
    

    Length of output: 566


    68-68: Check for any known issues with @opentelemetry/instrumentation-aws-sdk version 0.39.1 regarding AWS SDK calls.


    69-69: Verify that @opentelemetry/instrumentation-express is the appropriate version for the project's Express framework version.


    70-70: Ensure @opentelemetry/instrumentation-http is up-to-date and compatible with the project's HTTP handling.


    71-71: Confirm that @opentelemetry/instrumentation-nestjs-core integrates well with the project's NestJS version.


    72-72: Check if @opentelemetry/instrumentation-winston is compatible with the project's Winston logging setup.


    73-73: Ensure @opentelemetry/propagator-b3 is correctly configured for use in the project.

    Verification successful

    The verification process has confirmed that the @opentelemetry/propagator-b3 dependency is indeed configured for use in the project. The script found an import statement and a configuration line using B3Propagator in a file related to tracing, which matches the dependency mentioned in the package.json.

    Configuration of @opentelemetry/propagator-b3 verified successfully.

    • The dependency is imported and configured correctly in the project's tracing setup.
    Scripts Executed

    The following scripts were executed for the analysis:


    Script:

    #!/bin/bash
    # Description: Check the configuration of the B3 propagator in the tracing setup.
    
    # Test: Search for the B3 propagator configuration in the codebase.
    grep 'B3Propagator' src/traces/tracer.ts
    

    Length of output: 94



    Script:

    #!/bin/bash
    # Description: Locate and verify the configuration of the B3 propagator in the tracing setup.
    
    # Step 1: Find files related to tracing configuration
    fd 'tracer\.ts' --exec grep 'B3Propagator' {}
    

    Length of output: 149


    74-74: Verify the integration of @opentelemetry/resource-detector-docker with the Docker environment specified in the project.


    75-75: Confirm that @opentelemetry/resources is utilized effectively in the project's resource management.

    Verification successful

    The verification process has confirmed that the @opentelemetry/resources package is indeed utilized within the project. The file tracer.ts, which was initially not found due to an incorrect path, is located at services/workflows-service/src/traces/tracer.ts and it includes references to @opentelemetry/resources. This confirms the effective use of the package in the project's resource management.

    • The file tracer.ts is correctly located and uses @opentelemetry/resources.
    • The package is also referenced in services/workflows-service/package.json and pnpm-lock.yaml, indicating it is properly integrated and managed within the project's dependencies.
    Scripts Executed

    The following scripts were executed for the analysis:


    Script:

    #!/bin/bash
    # Description: Verify the use of OpenTelemetry resources in the project.
    
    # Test: Search for the usage of OpenTelemetry resources in the codebase.
    grep 'Resources' src/traces/tracer.ts
    

    Length of output: 91



    Script:

    #!/bin/bash
    # Description: Search for the file `tracer.ts` and usage of `@opentelemetry/resources` across the repository.
    
    # Find the file `tracer.ts` in the repository
    echo "Searching for tracer.ts in the repository:"
    fd tracer.ts
    
    # Search for the usage of `@opentelemetry/resources` in the codebase
    echo "Searching for usage of @opentelemetry/resources:"
    rg '@opentelemetry/resources' --files-with-matches
    

    Length of output: 418


    76-76: Check that @opentelemetry/sdk-node is set up correctly and functioning as expected in the project.


    77-77: Ensure that @opentelemetry/semantic-conventions are adhered to in the project's tracing and logging.


    79-79: Verify that @prisma/instrumentation is correctly integrated and functioning for database query tracing.

    Copy link
    Contributor

    @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

    Outside diff range and nitpick comments (3)
    services/workflows-service/src/common/app-logger/app-logger.service.ts (2)

    Line range hint 9-9: Decorators are not valid here. Please check the context or remove if misplaced.


    Line range hint 29-29: Avoid using any type for better type safety.

    - const payload: any = { ...this.getLogMetadata(), logData };
    + const payload: LogPayload = { ...this.getLogMetadata(), logData };
    services/workflows-service/src/sentry/sentry.service.ts (1)

    Line range hint 73-75: Avoid using any type to ensure type safety.

    - let user = this.cls.get('entity');
    - if (!user && request) {
    -   if (request.user) {
    -     user = request.user;
    -     // eslint-disable-next-line @typescript-eslint/no-explicit-any
    -   } else if ((request as any).tokenScope) {
    -     // eslint-disable-next-line @typescript-eslint/no-explicit-any
    -     user = (request as any).tokenScope;
    -   }
    - }
    + let user = this.cls.get('entity') || request?.user || request?.tokenScope;
    Tools
    Biome

    [error] 1-2: All these imports are only used as types.

    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

    Files that changed from the base of the PR and between 3c1d79f and 347c0cc.

    Files ignored due to path filters (1)
    • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
    Files selected for processing (6)
    • services/workflows-service/package.json (1 hunks)
    • services/workflows-service/prisma/data-migrations (1 hunks)
    • services/workflows-service/prisma/schema.prisma (1 hunks)
    • services/workflows-service/src/common/app-logger/app-logger.service.ts (1 hunks)
    • services/workflows-service/src/sentry/sentry.service.ts (2 hunks)
    • services/workflows-service/src/traces/tracer.ts (1 hunks)
    Files skipped from review due to trivial changes (2)
    • services/workflows-service/prisma/data-migrations
    • services/workflows-service/prisma/schema.prisma
    Additional context used
    Biome
    services/workflows-service/src/common/app-logger/app-logger.service.ts

    [error] 9-9: Decorators are not valid here.


    [error] 29-29: Unexpected any. Specify a different type.


    [error] 1-1: All these imports are only used as types.


    [error] 1-2: Some named imports are only used as types.


    [error] 2-3: All these imports are only used as types.

    services/workflows-service/src/sentry/sentry.service.ts

    [error] 73-73: Unexpected any. Specify a different type.


    [error] 75-75: Unexpected any. Specify a different type.


    [error] 1-2: All these imports are only used as types.

    services/workflows-service/src/traces/tracer.ts

    [error] 50-50: Unexpected any. Specify a different type.


    [error] 50-50: Unexpected any. Specify a different type.

    Additional comments not posted (3)
    services/workflows-service/src/common/app-logger/app-logger.service.ts (1)

    47-47: Ensure the new entity logic aligns with intended use cases.

    services/workflows-service/src/sentry/sentry.service.ts (1)

    47-53: Ensure trace ID retrieval and setting are robust and handle possible null values effectively.

    services/workflows-service/package.json (1)

    63-77: The new dependencies are appropriate for the OpenTelemetry integration.

    Copy link
    Contributor

    @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: 3

    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

    Files that changed from the base of the PR and between 347c0cc and e4607ee.

    Files ignored due to path filters (1)
    • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
    Files selected for processing (3)
    • services/workflows-service/package.json (1 hunks)
    • services/workflows-service/src/traces/http-intrumentation.ts (1 hunks)
    • services/workflows-service/src/traces/tracer.ts (1 hunks)
    Files skipped from review as they are similar to previous changes (1)
    • services/workflows-service/package.json
    Additional context used
    Biome
    services/workflows-service/src/traces/http-intrumentation.ts

    [error] 2-2: A Node.js builtin module should be imported with the node: protocol.


    [error] 1-2: All these imports are only used as types.

    services/workflows-service/src/traces/tracer.ts

    [error] 49-49: Unexpected any. Specify a different type.


    [error] 49-49: Unexpected any. Specify a different type.

    Additional comments not posted (3)
    services/workflows-service/src/traces/tracer.ts (3)

    19-19: Ensure the OTEL_EXPORTER_OTLP_TRACES_ENDPOINT environment variable is utilized for the endpoint configuration.


    49-52: Avoid using any type in requestHook to ensure type safety.

    Tools
    Biome

    [error] 49-49: Unexpected any. Specify a different type.


    [error] 49-49: Unexpected any. Specify a different type.


    57-62: Consider using a more robust logging framework instead of console.error for better error tracking and management in production environments.

    liorzblrn and others added 3 commits June 1, 2024 22:53
    Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
    …o/ballerine into bal-1657-otel-traces-support
    Copy link
    Contributor

    @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

    Outside diff range and nitpick comments (1)
    services/workflows-service/src/traces/http-intrumentation.ts (1)

    4-18: Consider adding type annotations to improve code readability and maintainability.

    const createFilter = (filters: RegExp[] | string[]): (url: string) => boolean => {
      // Function body remains the same
    };
    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

    Files that changed from the base of the PR and between e4607ee and 8738727.

    Files ignored due to path filters (1)
    • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
    Files selected for processing (2)
    • services/workflows-service/src/traces/http-intrumentation.ts (1 hunks)
    • services/workflows-service/src/traces/tracer.ts (1 hunks)
    Additional context used
    Biome
    services/workflows-service/src/traces/http-intrumentation.ts

    [error] 1-2: All these imports are only used as types.

    services/workflows-service/src/traces/tracer.ts

    [error] 52-52: Unexpected any. Specify a different type.


    [error] 52-52: Unexpected any. Specify a different type.

    Additional comments not posted (2)
    services/workflows-service/src/traces/tracer.ts (2)

    22-24: The implementation of getTracer function is correct and concise.


    26-57: The configuration of the OpenTelemetry SDK in tracingSdk is comprehensive and well-implemented.

    Tools
    Biome

    [error] 52-52: Unexpected any. Specify a different type.


    [error] 52-52: Unexpected any. Specify a different type.

    @@ -0,0 +1,33 @@
    import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
    import { IncomingMessage } from 'node:http';
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Use import type for imports that are only used for type information to optimize TypeScript compilation.

    - import { IncomingMessage } from 'node:http';
    + import type { IncomingMessage } from 'node:http';
    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.

    Suggested change
    import { IncomingMessage } from 'node:http';
    import type { IncomingMessage } from 'node:http';
    Tools
    Biome

    [error] 1-2: All these imports are only used as types.

    Comment on lines +60 to +65
    process.on('SIGTERM', () => {
    tracingSdk
    .shutdown()
    .then(() => console.log('Tracing terminated'))
    .catch((error: unknown) => console.error('Error terminating tracing', error));
    });
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Consider using a more robust logging framework instead of console.error for better error tracking and management in production environments.

    - .catch((error: unknown) => console.error('Error terminating tracing', error));
    + .catch((error: unknown) => logger.error('Error terminating tracing', error));

    Note: This suggestion assumes the existence of a logger object configured elsewhere in your application.

    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.

    Suggested change
    process.on('SIGTERM', () => {
    tracingSdk
    .shutdown()
    .then(() => console.log('Tracing terminated'))
    .catch((error: unknown) => console.error('Error terminating tracing', error));
    });
    process.on('SIGTERM', () => {
    tracingSdk
    .shutdown()
    .then(() => console.log('Tracing terminated'))
    .catch((error: unknown) => logger.error('Error terminating tracing', error));
    });

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    None yet

    4 participants