Skip to content

feat: add traces on migrations#374

Merged
gfyrag merged 1 commit into
mainfrom
feat/migrations-traces
Apr 1, 2025
Merged

feat: add traces on migrations#374
gfyrag merged 1 commit into
mainfrom
feat/migrations-traces

Conversation

@gfyrag
Copy link
Copy Markdown
Contributor

@gfyrag gfyrag commented Apr 1, 2025

No description provided.

@gfyrag gfyrag requested a review from a team as a code owner April 1, 2025 09:46
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 1, 2025

Warning

Rate limit exceeded

@gfyrag has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1207976 and 68ddbe7.

📒 Files selected for processing (2)
  • migrations/migrator.go (5 hunks)
  • otlp/error.go (1 hunks)

Walkthrough

The changes integrate OpenTelemetry tracing into the migration process. A new tracer field is added to the Migrator struct to support tracing capabilities. The NewMigrator function now accepts a WithTracer option that allows a tracer to be set during instantiation. Both the Up and UpByOne methods have been updated to initiate a tracing span at the start, set relevant schema attributes, record errors when applicable, and end the span appropriately. These modifications enhance the observability of migration operations by logging detailed trace information.

Changes

File Changes
migrations/migrator.go - Added tracer trace.Tracer field to the Migrator struct.
- Updated NewMigrator to accept the new WithTracer option.
- Introduced the WithTracer function.
- Modified Up and UpByOne to start and end tracing spans, set schema attributes, and record errors.
otlp/error.go - Updated RecordError method signature to accept variadic opts ...trace.EventOption.
- Added nil check for span in context to enhance robustness.
- Updated error recording to include provided options.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant M as Migrator
    participant T as Tracer
    participant S as Span

    C->>M: Call migration method (Up/UpByOne)
    M->>T: Start tracing span ("migrations.Up"/"migrations.UpByOne")
    T-->>M: Return Span
    M->>S: Set schema attributes
    alt Error occurs
        M->>S: Record error on span
    end
    M->>S: End span (defer)
    M-->>C: Return migration result
Loading

Poem

Hop along, dear coder friend,
I’m a rabbit on a trace-filled trend.
Logging hops with every step,
Tracing each migration adept.
With whiskers twitching, I cheer the light —
Code paths now clear and oh so bright!
🐰✨


🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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
Copy Markdown

@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 (5)
migrations/migrator.go (5)

167-170: Consider adding more trace attributes for better observability

The span creation and schema attribute look good. Consider enhancing the span with additional attributes such as the number of pending migrations or migration names to provide more context in traces.

 ctx, span := m.tracer.Start(ctx, "migrations.Up")
 defer span.End()

 span.SetAttributes(attribute.String("schema", m.GetSchema()))
+span.SetAttributes(attribute.Int("total_migrations", len(m.migrations)))

167-181: Consider recording errors in the Up method

You're correctly recording errors in the UpByOne method, but not in the Up method. For consistency, consider recording errors in the Up method as well.

 for {
     err := m.UpByOne(ctx)
     if err != nil {
         if errors.Is(err, ErrAlreadyUpToDate) {
             return nil
         }
+        span.RecordError(err)
         return err
     }
 }

405-408: Consider adding migration name to the trace

In the UpByOne method, when running a migration, consider adding the migration name and version to the trace span for better visibility in distributed tracing.

Add these lines after the start of the span (around line 429):

 ctx, span := m.tracer.Start(ctx, "migrations.UpByOne")
 defer span.End()

 span.SetAttributes(attribute.String("schema", m.GetSchema()))
+
+// Get the migration details before running it
+lastVersion, err := m.getLastVersion(ctx, m.rootDB)
+if err == nil && lastVersion+1 < len(m.migrations) {
+    span.SetAttributes(
+        attribute.Int("migration_version", lastVersion+1),
+        attribute.String("migration_name", m.migrations[lastVersion+1].Name),
+    )
+}

440-449: Consider adding nil check for tracer

While the default options provide a noop tracer, consider adding a safeguard in NewMigrator to ensure the tracer is never nil.

 func NewMigrator(db bun.IDB, opts ...Option) *Migrator {
     ret := &Migrator{
         rootDB:    db,
         tableName: migrationTable,
     }
     for _, opt := range append(defaultOptions, opts...) {
         opt(ret)
     }
+    // Ensure tracer is never nil
+    if ret.tracer == nil {
+        ret.tracer = noop.Tracer{}
+    }
     return ret
 }

1-474: Consider adding documentation for the tracing feature

The tracing implementation looks good, but consider adding documentation (either in code comments or README) on how users can leverage this new tracing capability. Include examples of how to initialize a Migrator with a custom tracer and how to visualize or analyze the generated traces.

Add a documentation comment above the WithTracer function:

+// WithTracer configures the Migrator to use the specified OpenTelemetry tracer.
+// This enables tracing of migration operations for better observability.
+// Example usage:
+//
+//   tracer := otel.GetTracerProvider().Tracer("my-service")
+//   migrator := NewMigrator(db, WithTracer(tracer))
 func WithTracer(tracer trace.Tracer) Option {
     return func(m *Migrator) {
         m.tracer = tracer
     }
 }
🧰 Tools
🪛 GitHub Actions: Default

[error] 1-1: There are changes in the repository that are not staged for commit. Please stage the changes before proceeding.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1119816 and 7b5b4c7.

📒 Files selected for processing (1)
  • migrations/migrator.go (5 hunks)
🧰 Additional context used
🪛 GitHub Actions: Default
migrations/migrator.go

[error] 1-1: There are changes in the repository that are not staged for commit. Please stage the changes before proceeding.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (6)
migrations/migrator.go (6)

7-9: Good addition of OpenTelemetry imports!

The imports for OpenTelemetry tracing look correct. You're importing the necessary packages for attributes, tracing, and the noop tracer implementation.


48-48: LGTM: Adding tracer field to Migrator struct

This is a good addition to support tracing capabilities in the migrator.


426-437: Good implementation of tracing in UpByOne method

The tracing implementation in UpByOne is well done. You're starting a span, setting attributes, recording errors (except for ErrAlreadyUpToDate which is an expected condition), and properly ending the span.


465-469: LGTM: WithTracer option function

The WithTracer option function is well implemented, following the existing pattern for options.


471-473: Good default with noop tracer

Setting a default noop tracer is a good practice to avoid nil pointer issues and ensure the code works even without an explicitly provided tracer.


1-474: Add tests for the tracing functionality

Consider adding tests to verify that the tracing functionality works as expected, including span creation, attribute setting, and error recording.

Since this PR adds a new feature (tracing), it would be beneficial to add tests to verify it works correctly. Can you confirm if you've added or plan to add tests for this functionality?

🧰 Tools
🪛 GitHub Actions: Default

[error] 1-1: There are changes in the repository that are not staged for commit. Please stage the changes before proceeding.

@gfyrag gfyrag force-pushed the feat/migrations-traces branch from 7b5b4c7 to e6c775b Compare April 1, 2025 09:59
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 1, 2025

Codecov Report

Attention: Patch coverage is 65.38462% with 9 lines in your changes missing coverage. Please review.

Project coverage is 34.55%. Comparing base (1119816) to head (68ddbe7).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
otlp/error.go 0.00% 5 Missing ⚠️
migrations/migrator.go 80.95% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #374      +/-   ##
==========================================
+ Coverage   34.40%   34.55%   +0.15%     
==========================================
  Files         112      112              
  Lines        4900     4922      +22     
==========================================
+ Hits         1686     1701      +15     
- Misses       3102     3108       +6     
- Partials      112      113       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gfyrag gfyrag force-pushed the feat/migrations-traces branch from e6c775b to 1207976 Compare April 1, 2025 12:55
Copy link
Copy Markdown

@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 (2)
otlp/error.go (2)

29-29: Consider updating RecordAsError implementation.

The calls to RecordError from RecordAsError don't pass any trace options. While this works (variadic parameters can be omitted), it might be good to explicitly pass an empty options slice for consistency and future-proofing.

- RecordError(ctx, ee)
+ RecordError(ctx, ee, []trace.EventOption{}...)

31-31: Same consideration for this RecordError call.

This call should also pass an empty options slice for consistency with the updated function signature.

- RecordError(ctx, fmt.Errorf("%s", e))
+ RecordError(ctx, fmt.Errorf("%s", e), []trace.EventOption{}...)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e6c775b and 1207976.

📒 Files selected for processing (2)
  • migrations/migrator.go (5 hunks)
  • otlp/error.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • migrations/migrator.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
otlp/error.go (3)

11-11: Function signature enhancement adds flexibility.

The updated signature with variadic trace.EventOption parameters allows callers to customize error recording behavior, aligning well with the OpenTelemetry tracing integration objectives.


16-18: Good defensive programming practice.

Adding a nil check for the span prevents potential panics if no valid span is available in the context, making the function more robust.


20-20: Enhanced error recording with flexible options.

The updated implementation properly combines user-provided options with the default stack trace option, maintaining backward compatibility while adding flexibility.

@gfyrag gfyrag force-pushed the feat/migrations-traces branch from 1207976 to 68ddbe7 Compare April 1, 2025 12:58
@gfyrag gfyrag added this pull request to the merge queue Apr 1, 2025
Merged via the queue into main with commit 7ef0885 Apr 1, 2025
8 checks passed
@gfyrag gfyrag deleted the feat/migrations-traces branch April 1, 2025 14:11
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