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

Validate dependsOn Field #477

Merged
merged 3 commits into from
Feb 12, 2025
Merged

Validate dependsOn Field #477

merged 3 commits into from
Feb 12, 2025

Conversation

mkysel
Copy link
Collaborator

@mkysel mkysel commented Feb 11, 2025

Summary by CodeRabbit

  • New Features

    • Introduced an enhanced state tracking mechanism that ensures improved validation and consistency during message processing and replication.
    • Added a cursor management feature to the replication and metadata services.
  • Refactor

    • Streamlined service initialization and dependency management for more reliable performance and graceful resource cleanup.
  • Tests

    • Enhanced the test suite with new scenarios to validate error handling related to cursor dependencies in the publishing process.

Copy link

coderabbitai bot commented Feb 11, 2025

Walkthrough

The pull request refactors cursor management across multiple components by introducing a new CursorUpdater interface with a concrete DBBasedCursorUpdater implementation. The Message and Metadata services have been updated to accept a CursorUpdater instance through their constructors, and the validation logic now uses this updater to verify envelope cursor positions. The ReplicationServer also integrates the CursorUpdater to manage its lifecycle, calling its Stop() method during shutdown. Additionally, test utilities are adjusted to construct the Metadata service with a CursorUpdater.

Changes

File(s) Change Summary
pkg/api/message/service.go Added new dependency import for metadata, introduced field cu in Service, updated NewReplicationApiService signature to accept metadata.CursorUpdater, enhanced validateClientInfo to retrieve and compare cursors, and replaced header creation in SubscribeEnvelopes.
pkg/api/metadata/(cursorUpdater.go, service.go) Introduced the CursorUpdater interface and its DBBasedCursorUpdater implementation with updated method signatures (including a new Stop() method) and constructor. Updated the Metadata service to use a value type for cu and accept a CursorUpdater instance instead of a SQL store.
pkg/server/server.go Added a new field cursorUpdater in the ReplicationServer. Initialized it via metadata.NewCursorUpdater and passed it to the API service constructors. Updated the Shutdown method to call cursorUpdater.Stop().
pkg/testutils/api/api.go Modified the Metadata service instantiation to pass a CursorUpdater instance (via metadata.NewCursorUpdater(ctx, log, db)) instead of the SQL database directly.
pkg/api/message/publish_test.go Added new test functions TestPublishEnvelopeBlockchainCursorAhead and TestPublishEnvelopeOriginatorUnknown to validate error handling in PublishPayerEnvelopes related to cursor dependencies. Introduced helper function publishPayerEnvelopeWithNodeIDAndCursor.

Possibly related PRs

Suggested reviewers

  • richardhuaaa
  • neekolas

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e2c21cf and b71ccae.

📒 Files selected for processing (2)
  • pkg/api/message/publish_test.go (1 hunks)
  • pkg/api/message/service.go (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test (Node)
🔇 Additional comments (6)
pkg/api/message/publish_test.go (3)

200-211: LGTM!

The test case effectively validates the error handling when a cursor references a sequence ID that hasn't been seen by the current node.


213-234: LGTM!

Well-structured helper function that follows the DRY principle by encapsulating common test setup logic.


236-247: LGTM!

The test case effectively validates the error handling when a cursor references an unknown originator node ID.

pkg/api/message/service.go (3)

7-7: LGTM!

Clean import changes that avoid naming conflicts.

Also applies to: 19-19


44-44: LGTM!

Clean integration of the CursorUpdater dependency into the Service struct and constructor.

Also applies to: 53-53, 72-72


456-474: LGTM!

The cursor validation logic is well-implemented with clear error messages. It properly validates:

  1. Node IDs in DependsOn have been seen
  2. Sequence IDs don't exceed last seen values
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

@mkysel mkysel force-pushed the mkysel/dependsonvalidation branch from 957ddcb to e2c21cf Compare February 11, 2025 15:00
Copy link

@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

🧹 Nitpick comments (6)
pkg/api/metadata/cursorUpdater.go (6)

14-19: Define interface contracts in comments for clarity.
It can be helpful to add a short docstring on each interface method explaining the high-level purpose—especially for Stop(), which is not immediately apparent from the name, to guide future contributors.


21-26: Ensure robust error handling and clarify concurrency model in constructor.

  1. The new fields cancel and wg facilitate graceful shutdown, but consider clarifying their usage in the struct-level comments.
  2. Inside NewCursorUpdater, any failure inside the goroutine started by tracing.GoPanicWrap will exit quietly if not properly handled. A structured error-handling approach or retry logic might be valuable.

Also applies to: 33-41, 45-51


61-79: Consider reacting to DB changes on-demand rather than a fixed ticker.
Although the 100 ms ticker works, it may incur unnecessary DB reads. If feasible, a DB trigger or a more event-driven approach could reduce overhead, especially under production load.


93-113: Add structured error handling and logging.
The TODO proper error handling comment indicates the need for a safer fallback or a backoff strategy. Logging the error and continuing vs. completely exiting might be preferable depending on business requirements.


115-129: Watch out for channel blocking in notifySubscribers().
If many subscribers exist and some are slow to receive, the loop might hold the lock for longer than desired. While the current implementation is acceptable, consider a more concurrent approach if usage grows.


137-141: Ensure explicit removal scenarios.
Clients that do not remove themselves (lack of RemoveSubscriber calls) can accumulate. If that’s acceptable, clarify usage in documentation. Otherwise, consider a time-based cleanup or heartbeat mechanism.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5f81ec and e2c21cf.

📒 Files selected for processing (5)
  • pkg/api/message/service.go (7 hunks)
  • pkg/api/metadata/cursorUpdater.go (4 hunks)
  • pkg/api/metadata/service.go (1 hunks)
  • pkg/server/server.go (4 hunks)
  • pkg/testutils/api/api.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test (Node)
🔇 Additional comments (9)
pkg/api/metadata/cursorUpdater.go (3)

55-59: Avoid returning a pointer to internal state if mutation is a concern.
Returning *envelopes.Cursor is fine, but keep in mind that future code might inadvertently mutate the returned struct. If that’s a concern, you could either clone the map or use a copy constructor.


131-135: Confirm safe handling for concurrent additions.
Locking is used here, which is good. However, if subscribers are frequently added or removed, consider verifying performance impact under high concurrency.


142-145: Graceful shutdown is well-implemented.
Calling cancel() and then wg.Wait() ensures no new operations occur while waiting for the existing goroutine to finish, preventing resource leaks.

pkg/api/metadata/service.go (1)

18-19: Confirm that storing the interface by value is intentional.
Using cu CursorUpdater avoids an extra level of indirection, which is usually fine. However, confirm that centralized updates to the cursor are still reflected across consumers.

Also applies to: 24-25, 29-29

pkg/testutils/api/api.go (1)

127-127: Reusing metadata.NewCursorUpdater is consistent.
Passing the same constructor into both replication and metadata services ensures a single source for cursor updates, aligning with the new architecture. Just confirm no separate, conflicting updaters are inadvertently created elsewhere.

Also applies to: 143-147

pkg/server/server.go (3)

50-50: LGTM! Field addition is well-placed.

The cursorUpdater field is appropriately added to the ReplicationServer struct, enabling cursor management functionality.


187-187: LGTM! Proper initialization and dependency injection.

The cursor updater is correctly initialized and injected into both the replication and metadata services, ensuring consistent cursor management across services.

Also applies to: 189-196, 204-208


286-288: LGTM! Clean resource management.

The Shutdown method properly cleans up the cursor updater resources, preventing potential resource leaks.

pkg/api/message/service.go (1)

44-44: LGTM! Clean integration of cursor updater.

The cu field is appropriately added to the Service struct, enabling cursor validation functionality.

@mkysel mkysel marked this pull request as ready for review February 11, 2025 20:39
@mkysel mkysel requested a review from a team as a code owner February 11, 2025 20:39
@@ -449,7 +453,25 @@ func (s *Service) validateClientInfo(clientEnv *envelopes.ClientEnvelope) error
return status.Errorf(codes.InvalidArgument, "topic does not match payload")
}

// TODO(rich): Verify all originators have synced past `last_seen`
if aad.GetDependsOn() != nil {
Copy link
Collaborator

Choose a reason for hiding this comment

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

LGTM.
Should we remove the aad.GetTargetOriginator() != s.registrant.NodeID() check on this PR?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah. That check will have to go. I need to introduce the new field set by the payer. I suspect we can still validate the originator if it exists for backwards compatibility?

Copy link
Contributor

Choose a reason for hiding this comment

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

Burn the boats. We're too early to worry about backward compatibility for things like validations that don't require coordination between nodes..

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It's tracked here #463

@mkysel mkysel merged commit bafe88f into main Feb 12, 2025
7 checks passed
@mkysel mkysel deleted the mkysel/dependsonvalidation branch February 12, 2025 15:29
@mkysel mkysel linked an issue Feb 14, 2025 that may be closed by this pull request
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.

Reject bogus dependencies
3 participants