8000 fix(temporal): fix workflow id too long error by paul-nicolas · Pull Request #304 · formancehq/payments · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix(temporal): fix workflow id too long error #304

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

Merged
merged 2 commits into from
Jan 30, 2025

Conversation

paul-nicolas
Copy link
Contributor

No description provided.

Copy link
Contributor
coderabbitai bot commented Jan 30, 2025

Warning

Rate limit exceeded

@paul-nicolas has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 20 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 91ff6cf and 25f0086.

📒 Files selected for processing (1)
  • internal/models/connectors.go (2 hunks)

Walkthrough

This pull request introduces a new Reference field to the Connector struct across multiple files in the internal package. The changes involve updating JSON marshaling, modifying task ID generation, adding a database column for connectors, creating a migration to populate the reference, and updating related tests. The modifications enhance the connector representation by adding a unique reference identifier that can be used throughout the application.

Changes

File Change Summary
internal/models/connectors.go Added Reference field to JSON marshaling
internal/models/task_id.go Modified TaskIDReference to include connector reference in ID generation
internal/storage/connectors.go Added Reference field to connector struct with UUID type
internal/storage/migrations/11-add-reference-for-connector.go Cre 8000 ated new migration to add and populate reference column
internal/storage/migrations/migrations.go Registered new migration for connector reference
internal/storage/migrations/migrations_test.go Added test hook to validate connector reference migration
test/e2e/api_bank_accounts_test.go Updated test to use new connector ID reference validation

Sequence Diagram

sequenceDiagram
    participant Connector as Connector Model
    participant Storage as Database
    participant Migration as Migration Process
    
    Connector->>Storage: Add Reference Column
    Migration->>Storage: Populate Reference for Existing Connectors
    Storage-->>Migration: Confirm Reference Population
    Connector->>Connector: Update JSON Marshaling
    Connector->>Connector: Modify Task ID Generation
Loading

Possibly related PRs

Suggested reviewers

  • laouji

Poem

🐰 A Rabbit's Ode to References New
With UUIDs dancing, connections so bright,
Our connectors now shine with reference's might.
Migrations leap forward, data pristine and clear,
A new identifier brings technical cheer!
Hop, hop, hooray for code so refined! 🚀


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 paul-nicolas force-pushed the fix/workflow-id-too-long branch 2 times, most recently from 3da547a to 46bcbd6 Compare January 30, 2025 12:33
@paul-nicolas
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor
coderabbitai bot commented Jan 30, 2025
✅ 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.

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 comments (2)
internal/storage/connectors.go (2)

Line range hint 193-204: Add Reference field to returned Connector model.

The ConnectorsGet method doesn't include the Reference field in the returned Connector model, which could cause issues if code depends on this field.

Apply this diff:

 return &models.Connector{
     ID:                   connector.ID,
+    Reference:            connector.Reference,
     Name:                 connector.Name,
     CreatedAt:            connector.CreatedAt.Time,
     Provider:             connector.Provider,
     Config:               connector.DecryptedConfig,
     ScheduledForDeletion: connector.ScheduledForDeletion,
 }, nil

Line range hint 251-267: Add Reference field to returned Connectors in list.

Similar to ConnectorsGet, the ConnectorsList method doesn't include the Reference field in the returned Connector models.

Apply this diff:

 for _, c := range cursor.Data {
     connectors = append(connectors, models.Connector{
         ID:                   c.ID,
+        Reference:            c.Reference,
         Name:                 c.Name,
         CreatedAt:            c.CreatedAt.Time,
         Provider:             c.Provider,
         Config:               c.DecryptedConfig,
         ScheduledForDeletion: c.ScheduledForDeletion,
     })
 }
🧹 Nitpick comments (1)
internal/storage/migrations/11-add-reference-for-connector.go (1)

18-25: Consider adding an index on the reference column.

Since the reference column is used in the TaskIDReference function, adding an index would improve query performance when looking up connectors by reference.

Add this to the migration:

 _, err := db.ExecContext(ctx, `
     ALTER TABLE connectors ADD COLUMN IF NOT EXISTS reference uuid;
+    CREATE INDEX IF NOT EXISTS idx_connectors_reference ON connectors(reference);
 `)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1582ce6 and 46bcbd6.

⛔ Files ignored due to path filters (2)
  • openapi.yaml is excluded by !**/*.yaml
  • openapi/v3/v3-schemas.yaml is excluded by !**/*.yaml
📒 Files selected for processing (7)
  • internal/models/connectors.go (1 hunks)
  • internal/models/task_id.go (1 hunks)
  • internal/storage/connectors.go (3 hunks)
  • internal/storage/migrations/11-add-reference-for-connector.go (1 hunks)
  • internal/storage/migrations/migrations.go (1 hunks)
  • internal/storage/migrations/migrations_test.go (2 hunks)
  • test/e2e/api_bank_accounts_test.go (1 hunks)
🔇 Additional comments (8)
internal/models/task_id.go (1)

18-18: LGTM! Verify backward compatibility of the new task ID format.

The change reduces the task ID length by using UUID reference instead of the full connector ID string, which should fix the "workflow id too long" error while maintaining uniqueness.

Let's verify the impact on existing task IDs:

✅ Verification successful

✅ Task ID format change is backward compatible

The new format maintains uniqueness while being shorter:

  • All callers provide full ConnectorID object
  • Function signature remains unchanged
  • New format separates provider from reference for better clarity
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing task ID usage patterns
rg -A 2 'TaskIDReference\(' .

Length of output: 1737

internal/storage/migrations/migrations.go (1)

159-169: LGTM! Migration is properly registered with transaction support.

The migration is well-structured with proper transaction handling and logging.

internal/storage/connectors.go (2)

38-38: LGTM! Reference field properly added to connector struct.

The Reference field is correctly added with appropriate type and constraints.


104-104: LGTM! Reference properly populated during installation.

The Reference field is correctly populated from the connector ID during installation.

test/e2e/api_bank_accounts_test.go (1)

139-140: LGTM! Test correctly validates the new reference-based task ID format.

The test modification properly verifies that task IDs now include the connector's reference string, which aligns with the workflow ID length fix.

internal/models/connectors.go (1)

31-31: LGTM! Reference field addition is well-implemented.

The Reference field is correctly added to the JSON representation and properly populated from the connector ID's reference.

Let's verify the impact on API consumers:

Also applies to: 39-39

✅ Verification successful

Reference field is read-only and safe to add

The Reference field is correctly implemented as a read-only, derived field that:

  • Is populated during JSON serialization from the existing ID field
  • Is not required during deserialization
  • Has no impact on API consumers as it's computed from existing data
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct JSON unmarshaling of Connector type
# to ensure consumers can handle the new field
rg -A 5 'json.Unmarshal.*Connector'

Length of output: 37


Script:

#!/bin/bash
# Search for Connector type usage in JSON context
echo "=== Searching for JSON handling of Connector type ==="
rg -g '!*.md' -i "json.*connector"

echo -e "\n=== Searching for Connector type in test files ==="
rg -g '*_test.go' "Connector"

echo -e "\n=== Looking for custom JSON methods on Connector ==="
ast-grep --pattern 'func ($_ *Connector) MarshalJSON() ([]byte, error)'
ast-grep --pattern 'func ($_ *Connector) UnmarshalJSON([]byte) error'

Length of output: 75004


Script:

#!/bin/bash
# Look for Connector type definition and its JSON methods
echo "=== Searching for Connector type definition ==="
rg -A 10 "type Connector struct"

echo -e "\n=== Searching for Connector JSON methods ==="
rg "func.*Connector.*JSON"

Length of output: 1169


Script:

#!/bin/bash
# Get the implementation of Connector's JSON methods
echo "=== Connector JSON method implementations ==="
rg -A 15 "func \(c .*Connector\).*JSON" internal/models/connectors.go

Length of output: 1437

internal/storage/migrations/migrations_test.go (2)

355-381: LGTM! Comprehensive migration test for connector references.

The test thoroughly validates that all connector types have correct reference values in the database after migration. Good error handling and assertions.


80-80: LGTM! Migration test properly registered.

The reference connector migration test is correctly registered in the test suite.

@paul-nicolas paul-nicolas force-pushed the fix/workflow-id-too-long branch from 46bcbd6 to c876bc8 Compare January 30, 2025 12:44
@paul-nicolas paul-nicolas marked this pull request as ready for review January 30, 2025 12:46
@paul-nicolas paul-nicolas requested a review from a team as a code owner January 30, 2025 12:46
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 (1)
internal/storage/migrations/migrations_test.go (1)

354-381: Consider enhancing test coverage with negative cases.

While the test effectively verifies the successful migration of connector references, it could be improved by:

  1. Testing for non-existent connectors
  2. Validating the format of the reference UUIDs
  3. Adding assertions for the total count of migrated records

Consider adding these test cases:

 func testReferenceConnectorMigrations() testmigrations.Hook {
 	return testmigrations.Hook{
 		After: func(ctx context.Context, t *testing.T, db bun.IDB) {
+			// Verify total count matches expected
+			count, err := db.NewSelect().TableExpr("connectors").Count(ctx)
+			require.NoError(t, err)
+			require.Equal(t, 10, count)
+
 			for _, connectorID := range []string{
 				// ... existing IDs ...
 			} {
 				id := models.MustConnectorIDFromString(connectorID)
+
+				// Validate UUID format
+				require.Regexp(t, "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", id.Reference.String())
 
 				exists, err := db.NewSelect().TableExpr("connectors").
 					Where("id = ?", connectorID).
 					Where("reference = ?", id.Reference).
 					Exists(ctx)
 				require.NoError(t, err)
 				require.True(t, exists)
 			}
+
+			// Test non-existent connector
+			exists, err := db.NewSelect().TableExpr("connectors").
+				Where("id = ?", "invalid-connector-id").
+				Exists(ctx)
+			require.NoError(t, err)
+			require.False(t, exists)
 		},
 	}
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 46bcbd6 and c876bc8.

⛔ Files ignored due to path filters (2)
  • openapi.yaml is excluded by !**/*.yaml
  • openapi/v3/v3-schemas.yaml is excluded by !**/*.yaml
📒 Files selected for processing (7)
  • internal/models/connectors.go (1 hunks)
  • internal/models/task_id.go (1 hunks)
  • internal/storage/connectors.go (3 hunks)
  • internal/storage/migrations/11-add-reference-for-connector.go (1 hunks)
  • internal/storage/migrations/migrations.go (1 hunks)
  • internal/storage/migrations/migrations_test.go (2 hunks)
  • test/e2e/api_bank_accounts_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/storage/connectors.go
  • internal/storage/migrations/migrations.go
  • internal/models/connectors.go
  • internal/models/task_id.go
  • test/e2e/api_bank_accounts_test.go
  • internal/storage/migrations/11-add-reference-for-connector.go
🔇 Additional comments (2)
internal/storage/migrations/migrations_test.go (2)

80-80: LGTM! Test integration looks good.

The new migration test is correctly integrated into the test suite with an appropriate sequence number.


370-370: Consider handling potential panic.

The MustConnectorIDFromString function will panic if the connector ID is invalid. While this might be acceptable in tests, it's good practice to handle potential errors gracefully.

Let's verify if there's error handling in the MustConnectorIDFromString function:

✅ Verification successful

Using MustConnectorIDFromString is appropriate in test code

The use of MustConnectorIDFromString is acceptable in this context because:

  1. This is test code where panics are acceptable and help identify issues quickly
  2. The connector ID is a hardcoded, known-valid test value
  3. This follows the common Go testing pattern where "Must" variants are used in tests
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the implementation of ConnectorIDFromString to check error ha
8000
ndling
ast-grep --pattern 'func $_(s string) ($_, error) {
  $$$
}'

Length of output: 3640


Script:

#!/bin/bash
# Search for both ConnectorIDFromString and MustConnectorIDFromString implementations
ast-grep --pattern 'func ConnectorIDFromString(s string) ($_, error) {
  $$$
}'

ast-grep --pattern 'func MustConnectorIDFromString(s string) $_ {
  $$$
}'

Length of output: 158


Script:

#!/bin/bash
# Search for both function names with context
rg -A 5 "ConnectorIDFromString" || true
rg -A 5 "MustConnectorIDFromString" || true

Length of output: 22325

@@ -28,13 +28,15 @@ func (c *Connector) IdempotencyKey() string {
func (c Connector) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
ID string `json:"id"`
Reference string `json:"reference"`
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't you add it to the unmarshal json func if you're adding it here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Since it's not present in the struct model, I think adding it to the unmarshal would be useless since we will not do anything with it !

Copy link
Contributor

Choose a reason for hiding this comment

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

But it should be symmetrical either way. If later we start using it it will be easier to create bugs because we forget there are some unaccounted for fields.

@paul-nicolas paul-nicolas force-pushed the fix/workflow-id-too-long branch from c876bc8 to 91ff6cf Compare January 30, 2025 13:11
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 (1)
internal/storage/migrations/migrations_test.go (1)

354-381: Consider enhancing test coverage and error handling.

While the basic implementation is solid, consider these improvements:

  1. Add negative test cases to verify that non-existent connectors are handled correctly
  2. Add test cases for malformed connector IDs
  3. Consider testing the actual reference values instead of just existence

Here's a suggested enhancement:

 func testReferenceConnectorMigrations() testmigrations.Hook {
 	return testmigrations.Hook{
 		After: func(ctx context.Context, t *testing.T, db bun.IDB) {
+			// Test valid connectors
 			for _, connectorID := range []string{
 				"eyJQcm92aWRlciI6Im1vbmV5Y29ycCIsIlJlZmVyZW5jZSI6IjdkNGU1MjM3LTNjMDktNDUwZS04ODY5LTI2YzA2MGFmMjM3NyJ9",
 				// ... other IDs ...
 			} {
 				id := models.MustConnectorIDFromString(connectorID)
 
 				exists, err := db.NewSelect().TableExpr("connectors").
 					Where("id = ?", connectorID).
 					Where("reference = ?", id.Reference).
 					Exists(ctx)
 				require.NoError(t, err)
 				require.True(t, exists)
+
+				// Verify the actual reference value
+				var reference string
+				err = db.NewSelect().TableExpr("connectors").
+					Column("reference").
+					Where("id = ?", connectorID).
+					Scan(ctx, &reference)
+				require.NoError(t, err)
+				require.Equal(t, id.Reference, reference)
 			}
+
+			// Test non-existent connector
+			exists, err := db.NewSelect().TableExpr("connectors").
+				Where("id = ?", "non-existent-id").
+				Exists(ctx)
+			require.NoError(t, err)
+			require.False(t, exists)
+
+			// Test malformed connector ID
+			exists, err = db.NewSelect().TableExpr("connectors").
+				Where("id = ?", "malformed-id").
+				Exists(ctx)
+			require.NoError(t, err)
+			require.False(t, exists)
 		},
 	}
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c876bc8 and 91ff6cf.

⛔ Files ignored due to path filters (2)
  • openapi.yaml is excluded by !**/*.yaml
  • openapi/v3/v3-schemas.yaml is excluded by !**/*.yaml
📒 Files selected for processing (7)
  • internal/models/connectors.go (1 hunks)
  • internal/models/task_id.go (1 hunks)
  • internal/storage/connectors.go (3 hunks)
  • internal/storage/migrations/11-add-reference-for-connector.go (1 hunks)
  • internal/storage/migrations/migrations.go (1 hunks)
  • internal/storage/migrations/migrations_test.go (2 hunks)
  • test/e2e/api_bank_accounts_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/models/connectors.go
  • internal/storage/migrations/migrations.go
  • internal/storage/migrations/11-add-reference-for-connector.go
  • internal/models/task_id.go
  • internal/storage/connectors.go
  • test/e2e/api_bank_accounts_test.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests
🔇 Additional comments (1)
internal/storage/migrations/migrations_test.go (1)

80-80: LGTM! Test integration looks good.

The new migration test is correctly integrated into the test suite with an appropriate sequence number.

@paul-nicolas paul-nicolas merged commit 0a05349 into main Jan 30, 2025
7 checks passed
@paul-nicolas paul-nicolas deleted the fix/workflow-id-too-long branch January 30, 2025 13:53
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
0