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

fix(temporal): fix missing reference storage error #214

Merged
merged 1 commit into from
Dec 17, 2024

Conversation

paul-nicolas
Copy link
Contributor

We launch the schedule before inserting it in the
database, so we can have instances inserted before schedule is inserted leading to errors.

Fixes ENG-1569

We launch the schedule before inserting it in the
database, so we can have instances inserted before
schedule is inserted leading to errors.
Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

Walkthrough

The pull request introduces changes to the scheduling process across multiple files in the internal connectors engine. The primary modification involves reordering the schedule creation workflow by first storing the schedule in persistent storage using activities.StorageSchedulesStore before creating a temporal schedule. Additionally, the TemporalScheduleCreate function's signature has been updated to return only an error, removing the schedule ID return value. These changes aim to improve error handling and ensure proper schedule persistence before temporal scheduling.

Changes

File Change Summary
internal/connectors/engine/activities/temporal_schedule_create.go Modified function signature to return only error instead of (string, error)
internal/connectors/engine/workflow/create_payout.go Added schedule storage before temporal schedule creation
internal/connectors/engine/workflow/create_transfer.go Added schedule storage before temporal schedule creation
internal/connectors/engine/workflow/plugin_workflow.go Reordered schedule creation to store schedule first, then create temporal schedule

Assessment against linked issues

Objective Addressed Explanation
Fix storage error with missing reference [ENG-1569]

Poem

🐰 Schedules dancing, order refined
Storage first, then temporal design
Errors caught with rabbit's keen sight
Code flows smoother, future bright
A scheduling ballet, clean and tight! 🎉

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@paul-nicolas
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@paul-nicolas paul-nicolas marked this pull request as ready for review December 17, 2024 11:01
@paul-nicolas paul-nicolas requested a review from a team as a code owner December 17, 2024 11:01
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

🧹 Nitpick comments (3)
internal/connectors/engine/workflow/create_payout.go (1)

Line range hint 125-159: Consider wrapping both operations in a transaction-like pattern

While the sequential operations fix the immediate race condition, consider implementing a more robust pattern to handle failures between storage and temporal creation.

Consider implementing a cleanup mechanism in case temporal schedule creation fails:

 err = activities.StorageSchedulesStore(...)
 if err != nil {
     return err
 }

 err = activities.TemporalScheduleCreate(...)
 if err != nil {
+    // Cleanup the stored schedule if temporal creation fails
+    cleanupErr := activities.StorageSchedulesDelete(
+        infiniteRetryContext(ctx),
+        scheduleID,
+    )
+    if cleanupErr != nil {
+        // Log cleanup error but return original error
+        workflow.GetLogger(ctx).Error("Failed to cleanup schedule after temporal creation failed",
+            "scheduleID", scheduleID,
+            "error", cleanupErr)
+    }
     return err
 }
internal/connectors/engine/workflow/plugin_workflow.go (1)

Line range hint 118-148: Consider consistent error handling pattern across workflows

Similar to the create_payout workflow, consider implementing the same robust cleanup pattern here.

Consider implementing the same cleanup mechanism in case temporal schedule creation fails:

 err = activities.StorageSchedulesStore(...)
 if err != nil {
     return err
 }

 err = activities.TemporalScheduleCreate(...)
 if err != nil {
+    // Cleanup the stored schedule if temporal creation fails
+    cleanupErr := activities.StorageSchedulesDelete(
+        infiniteRetryContext(ctx),
+        scheduleID,
+    )
+    if cleanupErr != nil {
+        // Log cleanup error but return original error
+        workflow.GetLogger(ctx).Error("Failed to cleanup schedule after temporal creation failed",
+            "scheduleID", scheduleID,
+            "error", cleanupErr)
+    }
     return err
 }
internal/connectors/engine/workflow/create_transfer.go (1)

116-127: Consider improving error handling and timestamp consistency.

A few suggestions for improvement:

  1. Consider adding cleanup logic for the stored schedule if temporal schedule creation fails
  2. Ensure consistent usage of UTC timestamps across both storage and schedule creation
  3. Consider validating the schedule ID for special characters that might cause issues

Here's a suggested improvement:

 err = activities.StorageSchedulesStore(
   infiniteRetryContext(ctx),
   models.Schedule{
     ID:          scheduleID,
     ConnectorID: createTransfer.ConnectorID,
     CreatedAt:   workflow.Now(ctx).UTC(),
   })
 if err != nil {
   return err
 }

+// Ensure cleanup if temporal schedule creation fails
 err = activities.TemporalScheduleCreate(
   infiniteRetryContext(ctx),
   activities.ScheduleCreateOptions{
     ScheduleID: scheduleID,
     // ... other options ...
   },
 )
 if err != nil {
+  // Attempt to clean up the stored schedule
+  if cleanupErr := activities.StorageSchedulesDelete(
+    infiniteRetryContext(ctx),
+    scheduleID,
+  ); cleanupErr != nil {
+    return fmt.Errorf("schedule creation failed: %v, cleanup failed: %v", err, cleanupErr)
+  }
   return err
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b2efaf5 and 499bfaa.

📒 Files selected for processing (4)
  • internal/connectors/engine/activities/temporal_schedule_create.go (3 hunks)
  • internal/connectors/engine/workflow/create_payout.go (1 hunks)
  • internal/connectors/engine/workflow/create_transfer.go (1 hunks)
  • internal/connectors/engine/workflow/plugin_workflow.go (1 hunks)
🔇 Additional comments (6)
internal/connectors/engine/activities/temporal_schedule_create.go (2)

Line range hint 23-52: LGTM! Function signature simplified to focus on error handling

The removal of the schedule ID return value is a good change since the ID is now managed externally, making the function more focused.


57-61: LGTM! Workflow helper updated consistently

The workflow helper function has been updated to match the new signature, maintaining consistency.

internal/connectors/engine/workflow/create_payout.go (1)

113-124: LGTM! Schedule storage added before temporal creation

Good addition of schedule storage before temporal creation to prevent race conditions.

internal/connectors/engine/workflow/plugin_workflow.go (2)

107-116: LGTM! Schedule storage added before temporal creation

Good addition of schedule storage before temporal creation to prevent race conditions.


Line range hint 107-148: Verify the impact of jitter on schedule creation

The addition of jitter might affect the timing of schedule execution.

Let's verify the jitter configuration across the codebase:

✅ Verification successful

Jitter configuration is consistently implemented and safe

The verification shows that:

  • Jitter is consistently set to half of the polling period (config.PollingPeriod / 2)
  • The polling period has a minimum safety threshold of 30 seconds as enforced in internal/models/config.go
  • The jitter configuration is properly passed through to the temporal schedule creation activity
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for jitter configurations in schedule creation
# to ensure consistent usage across the codebase

# Search for jitter configurations in schedule creation
rg -A 2 "Jitter:\s+" 

# Search for PollingPeriod configurations to verify jitter calculation
rg "PollingPeriod"

Length of output: 4400

internal/connectors/engine/workflow/create_transfer.go (1)

115-125: LGTM! The schedule storage implementation fixes the reference issue.

The implementation correctly addresses the core issue by ensuring the schedule is stored in persistent storage before creating the temporal schedule. The error handling ensures atomic operations.

Let's verify the schedule storage implementation:

✅ Verification successful

Schedule storage implementation is correctly synchronized across the codebase

Based on the verification results, the implementation follows a consistent pattern across all workflow files (create_transfer.go, create_payout.go, and plugin_workflow.go). In each case:

  • The schedule is stored in persistent storage using StorageSchedulesStore before creating the temporal schedule
  • The same error handling pattern and UTC timestamp usage is maintained
  • Schedule IDs follow a consistent format with proper namespacing

Key findings:

  • All three workflow files that use TemporalScheduleCreate properly store schedules first
  • The error handling pattern is consistent across all implementations
  • The activity registration in activity.go confirms proper integration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the schedule storage implementation across the codebase
# Check for consistent schedule storage pattern and potential race conditions

# Check for other places where TemporalScheduleCreate is used without StorageSchedulesStore
ast-grep --pattern 'activities.TemporalScheduleCreate($$$)' | grep -B 5 'TemporalScheduleCreate' | grep -v 'StorageSchedulesStore'

# Check for proper error handling pattern
ast-grep --pattern 'err := activities.StorageSchedulesStore($$$)
if err != nil {
  return err
}'

Length of output: 227


Script:

#!/bin/bash
# Let's try a different approach to verify the schedule storage implementation

# 1. Find all files that use TemporalScheduleCreate
rg "TemporalScheduleCreate" -l

# 2. Search for the pattern with more context
rg "TemporalScheduleCreate" -A 5 -B 5

# 3. Look for StorageSchedulesStore usage
rg "StorageSchedulesStore" -A 5 -B 5

# 4. Find all workflow files that might handle schedules
fd "workflow.*\.go$"

Length of output: 12760

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