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

Read your own commits - Stage 1 #438

Merged
merged 9 commits into from
Jan 29, 2025
Merged

Read your own commits - Stage 1 #438

merged 9 commits into from
Jan 29, 2025

Conversation

mkysel
Copy link
Collaborator

@mkysel mkysel commented Jan 28, 2025

Depends on xmtp/proto#241

This adds a new metadata service to the XMTPD GRPC API which exposes the current last synced vector/cursor.

The next PR will teach the payer how to subscribe to this to have some sort of read-your-own-commits guarantees. At least for early stages of development while the client expects these.

Summary by CodeRabbit

  • New Features

    • Added metadata API configuration options
    • Introduced cursor tracking and synchronization functionality
    • Enabled optional metadata service for the server
  • Configuration

    • New environment variables for enabling metadata features
    • Added metadata-related configuration options
  • Backend Improvements

    • Implemented cursor updater for tracking sequence IDs
    • Added database query for retrieving latest cursor information

@mkysel mkysel requested a review from a team as a code owner January 28, 2025 17:57
Copy link

coderabbitai bot commented Jan 28, 2025

Warning

Rate limit exceeded

@mkysel has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 44 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 793f21b and 7736d22.

📒 Files selected for processing (1)
  • pkg/api/metadata/cursorUpdater.go (1 hunks)

Walkthrough

This pull request introduces a new metadata service for the XMTPD system. The changes include adding environment variable exports to enable metadata and reflection, creating a new CursorUpdater for tracking sequence IDs, implementing a gRPC metadata service, and updating configuration options to support the new metadata functionality. The modifications extend the system's capabilities by providing a mechanism for synchronizing and tracking metadata across different nodes.

Changes

File Change Summary
dev/run Added two new environment variable exports: XMTPD_REFLECTION_ENABLE and XMTPD_METADATA_ENABLE
pkg/api/metadata/cursorUpdater.go New file introducing CursorUpdater type with methods for managing and updating cursor state
pkg/api/metadata/service.go Implemented metadata gRPC service with GetSyncCursor and SubscribeSyncCursor methods
pkg/config/options.go Added MetadataOptions and updated ServerOptions to include metadata configuration
pkg/config/validation.go Enhanced validation to check WriterConnectionString when metadata is enabled
pkg/db/queries.sql Added new SQL query GetLatestCursor to retrieve maximum sequence IDs
pkg/db/queries/queries.sql.go Generated Go code for the new GetLatestCursor query
pkg/server/server.go Updated server initialization to support metadata service registration

Sequence Diagram

sequenceDiagram
    participant Client
    participant MetadataService
    participant CursorUpdater
    participant Database

    Client->>MetadataService: SubscribeSyncCursor()
    MetadataService->>CursorUpdater: AddSubscriber()
    CursorUpdater->>Database: Periodically read latest cursor
    Database-->>CursorUpdater: Return latest cursor data
    CursorUpdater->>CursorUpdater: Update internal cursor
    CursorUpdater->>Client: Send cursor updates
Loading

Possibly related PRs

Suggested reviewers

  • neekolas

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.

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

🧹 Nitpick comments (5)
pkg/api/metadata/service.go (3)

15-20: Consider clarifying field naming.

It might be more descriptive to rename the cu field in the Service struct to something like cursorUpdater or updater to reflect its purpose more clearly.


22-32: Add error-handling for NewCursorUpdater.

The constructor Func NewMetadataApiService returns a Service after calling NewCursorUpdater, but any errors from creating or initializing the cursor updater might be lost if NewCursorUpdater were to return an error in future changes. Consider handling potential future errors in this flow or making the constructor safer to reflect initialization failures.


44-83: Evaluate subscriber-based streaming load.

While this subscription model is straightforward and functional, consider situations with a large number of clients subscribing concurrently. The current approach spawns a unique channel per subscriber, potentially leading to high memory usage if the number of subscribers grows. A shared publish/subscribe mechanism or event bus might be more efficient for large-scale scenarios.

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

75-89: Optimize subscriber notifications.

In notifySubscribers(), every subscriber gets notified on every read cycle. If you plan to increase the ticker frequency or have many subscribers, consider batching or combining notifications (e.g., only send if the cursor value changed). This can help reduce load on the many channels summoned here.

pkg/db/queries.sql (1)

Line range hint 100-136: Consider caching strategy for cursor updates.

For the read-your-own-writes guarantee mentioned in the PR objectives, consider the following architectural aspects:

  1. Implement appropriate caching with a configurable TTL to balance freshness vs performance
  2. Add appropriate locking mechanisms to prevent race conditions during cursor updates
  3. Consider adding a mechanism to force cursor refresh when a client writes data, ensuring immediate visibility of their own writes
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between caf2078 and 2da12ed.

⛔ Files ignored due to path filters (4)
  • pkg/proto/openapi/xmtpv4/metadata_api/metadata_api.swagger.json is excluded by !pkg/proto/**
  • pkg/proto/xmtpv4/metadata_api/metadata_api.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • pkg/proto/xmtpv4/metadata_api/metadata_api.pb.gw.go is excluded by !**/*.pb.gw.go, !pkg/proto/**
  • pkg/proto/xmtpv4/metadata_api/metadata_api_grpc.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
📒 Files selected for processing (9)
  • dev/gen-protos (1 hunks)
  • dev/run (1 hunks)
  • pkg/api/metadata/cursorUpdater.go (1 hunks)
  • pkg/api/metadata/service.go (1 hunks)
  • pkg/config/options.go (2 hunks)
  • pkg/config/validation.go (1 hunks)
  • pkg/db/queries.sql (1 hunks)
  • pkg/db/queries/queries.sql.go (1 hunks)
  • pkg/server/server.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test (Node)
  • GitHub Check: Build pre-baked anvil-xmtpd
🔇 Additional comments (10)
dev/gen-protos (1)

4-4: Validate branch availability.

Referencing the mkysel/metadata-endpoint branch is fine, but ensure it’s consistently updated or merged to avoid version mismatches during protobuf generation.

dev/run (1)

7-12: LGTM! Environment variables are properly configured.

The addition of XMTPD_METADATA_ENABLE aligns with the PR objectives to enable the metadata service, and XMTPD_REFLECTION_ENABLE is beneficial for development and debugging.

pkg/config/validation.go (1)

62-66: LGTM! Validation logic is consistent and complete.

The validation ensures that the required database connection is available when the metadata service is enabled, following the same pattern as other services.

pkg/server/server.go (2)

19-19: LGTM! Required imports are properly added.

The metadata-related package imports are correctly added.

Also applies to: 29-29


129-129: LGTM! API server condition is properly updated.

The condition is correctly extended to include the metadata service.

pkg/config/options.go (2)

54-56: LGTM! MetadataOptions type is well-defined.

The type follows the established pattern and includes clear documentation.


87-87: LGTM! ServerOptions is properly updated.

The Metadata field is correctly added with appropriate group and namespace, maintaining the struct's organization.

pkg/db/queries/queries.sql.go (2)

110-113: LGTM! Implementation follows best practices.

The Go implementation follows proper error handling patterns and resource management.

Also applies to: 115-136


100-108: LGTM! Query implementation looks correct.

The SQL query is well-structured and uses appropriate type casting.

Let's verify the query performance on large datasets:

✅ Verification successful

Query performance verified - optimal execution plan expected

The query will efficiently use the primary key index (originator_node_id, originator_sequence_id) for both grouping and MAX aggregation, ensuring good performance even on large datasets.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the query execution plan and table statistics
# to ensure efficient execution on large datasets

# Check if there's an index on originator_node_id
rg -A 5 "CREATE.*INDEX.*originator_node_id" .

# Look for table creation to understand the schema
rg -A 10 "CREATE.*TABLE.*gateway_envelopes" .

Length of output: 922

pkg/db/queries.sql (1)

125-132: LGTM! SQL query definition is well-structured.

The query follows the established patterns in the file and uses appropriate type annotations.

Comment on lines 37 to 53
func (cu *CursorUpdater) start() {
ticker := time.NewTicker(100 * time.Millisecond) // Adjust the period as needed
defer ticker.Stop()
for {
select {
case <-cu.ctx.Done():
return
case <-ticker.C:
err := cu.read()
if err != nil {
//TODO proper error handling
return
}
cu.notifySubscribers()
}
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Provide resiliency to transient read failures.

The start method stops processing at line 48 if cu.read() returns an error. Consider logging the error and continuing to retry instead of ceasing the entire updater. In production, transient database failures could cause the service to terminate prematurely.

pkg/api/metadata/cursorUpdater.go Outdated Show resolved Hide resolved
pkg/server/server.go Outdated Show resolved Hide resolved
@mkysel
Copy link
Collaborator Author

mkysel commented Jan 28, 2025

$ grpcurl -plaintext -d '{}' localhost:5050 xmtp.xmtpv4.metadata_api.MetadataApi/SubscribeSyncCursor
{
  "latestSync": {
    "nodeIdToSequenceId": {
      "1": "12",
      "100": "12"
    }
  }
}

@@ -124,7 +126,7 @@ func NewReplicationServer(
log.Info("Indexer service enabled")
}

if options.Payer.Enable || options.Replication.Enable {
if options.Payer.Enable || options.Replication.Enable || options.Metadata.Enable {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should we simplify this by including the metadata api every time payer and/or replication are enabled? I think we might be overcomplicating this.

pkg/api/metadata/cursorUpdater.go Outdated Show resolved Hide resolved
pkg/api/metadata/cursorUpdater.go Outdated Show resolved Hide resolved
mkysel and others added 3 commits January 29, 2025 08:02
Co-authored-by: Francisco de Borja Aranda Castillejo <[email protected]>
Co-authored-by: Francisco de Borja Aranda Castillejo <[email protected]>
@mkysel mkysel merged commit 868beb7 into main Jan 29, 2025
8 checks passed
@mkysel mkysel deleted the mkysel/read-your-own-commits branch January 29, 2025 16:10
@mkysel
Copy link
Collaborator Author

mkysel commented Jan 29, 2025

Relates to #418

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