Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Link payer to gateway envelopes #536

Draft
wants to merge 1 commit into
base: 02-21-add_payers_table
Choose a base branch
from

Conversation

neekolas
Copy link
Contributor

@neekolas neekolas commented Feb 21, 2025

TL;DR

Added payer tracking to gateway envelopes by linking them to payer records in the database.

It's very hard to fill this link in after-the-fact, since it requires recovering the signer address from the PayerEnvelope, so I think it makes sense to store it on every row even if we don't have an immediate use for querying by the field.

Issues

What changed?

  • Added a payer_id column to the gateway_envelopes table that references the payers table
  • Modified the InsertGatewayEnvelope query to include the payer_id field
  • Updated the publish worker and sync worker to extract payer information from envelopes and store it
  • Added validation of originator envelopes before processing
  • Updated tests to include payer IDs in test data

How to test?

  • Run existing test suite which has been updated to include payer tracking
  • Verify that gateway envelopes are properly linked to payer records
  • Confirm that invalid envelopes are rejected during validation
  • Check that payer addresses are correctly recovered from signatures

Why make this change?

This change enables tracking of message payers in the system, which is essential for:

  • Monitoring message usage per payer
  • Supporting future billing and rate limiting features
  • Improving system accountability and auditability

Copy link

coderabbitai bot commented Feb 21, 2025

Warning

Rate limit exceeded

@neekolas has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 17 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 9eb284b and 635853b.

📒 Files selected for processing (12)
  • pkg/api/message/publishWorker.go (3 hunks)
  • pkg/api/message/subscribe_test.go (6 hunks)
  • pkg/api/metadata/cursor_test.go (6 hunks)
  • pkg/api/query_test.go (6 hunks)
  • pkg/db/queries.sql (1 hunks)
  • pkg/db/queries/models.go (1 hunks)
  • pkg/db/queries/queries.sql.go (5 hunks)
  • pkg/migrations/00006_link-payer-to-gateway-envelopes.down.sql (1 hunks)
  • pkg/migrations/00006_link-payer-to-gateway-envelopes.up.sql (1 hunks)
  • pkg/sync/syncWorker.go (3 hunks)
  • pkg/testutils/envelopes/envelopes.go (2 hunks)
  • pkg/testutils/store.go (1 hunks)

Walkthrough

The changes introduce a new payer identifier into the gateway envelope processing flow. The modifications update envelope validation in the publish and sync workers by verifying and recovering the payer address, which is then used to look up or create a payer entry in the database. Corresponding SQL queries, data models, and migration scripts have been updated to add the new payer_id column. Test setups in several files now include the payer identifier for envelope parameters, and a new test helper function is provided to create or retrieve a payer.

Changes

File(s) Change Summary
pkg/api/message/publishWorker.go Updated publishStagedEnvelope to validate the originator envelope using envelopes.NewOriginatorEnvelope, recover the payer address, retrieve/create a payer (FindOrCreatePayer), and pass the resulting PayerID to InsertGatewayEnvelope.
pkg/api/message/subscribe_test.go
pkg/api/metadata/cursor_test.go
pkg/api/query_test.go
Modified test setups to include a new payerId variable. Updated instances of InsertGatewayEnvelopeParams to incorporate the PayerID and adjusted function return values to provide additional test context.
pkg/db/queries.sql
pkg/db/queries/models.go
pkg/db/queries/queries.sql.go
Added a new column payer_id to the SQL INSERT and SELECT statements for gateway_envelopes. Updated the GatewayEnvelope struct and related parameter structs to include PayerID (of type sql.NullInt32).
pkg/migrations/00006_link-payer-to-gateway-envelopes.up.sql
pkg/migrations/00006_link-payer-to-gateway-envelopes.down.sql
Introduced migration scripts to add (up) and drop (down) the payer_id column in the gateway_envelopes table.
pkg/sync/syncWorker.go Added a new method getPayerID that recovers the payer address from an envelope and queries the database to find or create a corresponding payer. Integrated this method into the insertEnvelope process to include the payer ID in database inserts.
pkg/testutils/store.go Added a new function CreatePayer to facilitate the creation or retrieval of a payer in tests by querying the database with a provided or generated address.

Sequence Diagram(s)

sequenceDiagram
    participant PW as PublishWorker
    participant EV as EnvelopeValidator
    participant PE as PayerEnvelope
    participant DB as Database

    PW->>EV: NewOriginatorEnvelope(originatorEnv)
    EV-->>PW: validatedEnvelope
    PW->>PE: RecoverSigner() from validatedEnvelope
    PE-->>PW: payerAddress
    PW->>DB: FindOrCreatePayer(ctx, payerAddress.Hex())
    DB-->>PW: payerID
    PW->>DB: InsertGatewayEnvelope(..., payerID)
Loading
sequenceDiagram
    participant SW as SyncWorker
    participant PE as PayerEnvelope
    participant DB as Database

    SW->>PE: Extract payer address from OriginatorEnvelope
    PE-->>SW: payerAddress
    SW->>DB: FindOrCreatePayer(ctx, payerAddress.Hex())
    DB-->>SW: payerID
    SW->>DB: Insert envelope with payerID
Loading

Possibly related PRs

Suggested reviewers

  • fbac
  • mkysel

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
Contributor Author

neekolas commented Feb 21, 2025

Warning

This pull request is not mergeable via GitHub because a downstack PR is open. Once all requirements are satisfied, merge this PR as a stack on Graphite.
Learn more

This stack of pull requests is managed by Graphite. Learn more about stacking.

@neekolas neekolas mentioned this pull request Feb 21, 2025
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: 0

🧹 Nitpick comments (3)
pkg/api/message/publishWorker.go (1)

92-96: Consider adding a retry limit or backoff strategy.

The infinite retry loop could be problematic if there are persistent validation failures. Consider implementing:

  • A maximum retry limit
  • An exponential backoff strategy
  • A dead letter queue for failed messages
pkg/sync/syncWorker.go (1)

438-442: Enhance error logging for payer ID failures.

The error logging could be more descriptive to help with debugging. Consider including the envelope details in the error log.

-    s.log.Error("Failed to get payer ID", zap.Error(err))
+    s.log.Error("Failed to get payer ID",
+        zap.Error(err),
+        zap.Uint32("originatorNodeID", env.OriginatorNodeID()),
+        zap.Uint64("originatorSequenceID", env.OriginatorSequenceID()))
pkg/migrations/00006_link-payer-to-gateway-envelopes.up.sql (1)

1-3: SQL Migration: Adding Nullable payer_id Column
The migration file correctly alters the gateway_envelopes table by adding a new nullable column payer_id of type INT with a foreign key reference to payers(id). The inline comment clarifies that blockchain-originated messages won’t provide a payer_id, which improves clarity.

Suggestion: Consider evaluating whether an index on payer_id might enhance query performance if future queries filter or join on this column.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1758eb6 and 9eb284b.

📒 Files selected for processing (11)
  • pkg/api/message/publishWorker.go (3 hunks)
  • pkg/api/message/subscribe_test.go (6 hunks)
  • pkg/api/metadata/cursor_test.go (6 hunks)
  • pkg/api/query_test.go (6 hunks)
  • pkg/db/queries.sql (1 hunks)
  • pkg/db/queries/models.go (1 hunks)
  • pkg/db/queries/queries.sql.go (5 hunks)
  • pkg/migrations/00006_link-payer-to-gateway-envelopes.down.sql (1 hunks)
  • pkg/migrations/00006_link-payer-to-gateway-envelopes.up.sql (1 hunks)
  • pkg/sync/syncWorker.go (3 hunks)
  • pkg/testutils/store.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • pkg/migrations/00006_link-payer-to-gateway-envelopes.down.sql
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build pre-baked anvil-xmtpd
  • GitHub Check: Test (Node)
🔇 Additional comments (9)
pkg/db/queries/models.go (1)

33-33: LGTM!

The PayerID field is correctly defined as a nullable integer using sql.NullInt32.

pkg/testutils/store.go (1)

114-127: LGTM!

The CreatePayer test helper function is well-implemented:

  • Handles both cases: with and without provided address
  • Uses correct address length (42 chars) for random generation
  • Properly handles errors
pkg/api/message/publishWorker.go (1)

113-147: LGTM! Robust validation and payer linking implementation.

The changes introduce proper:

  • Envelope validation
  • Payer address recovery
  • Database operations for payer linking
  • Error handling at each step
pkg/api/metadata/cursor_test.go (1)

31-33: LGTM! Test setup properly integrates payer ID.

The changes correctly:

  • Create a payer during test setup
  • Add payer ID to all test data rows
  • Maintain proper cleanup chain

Also applies to: 40-41, 50-51, 61-62, 71-72, 81-82, 89-89

pkg/api/query_test.go (1)

27-28: LGTM! Test setup correctly initializes payer ID.

The test setup properly creates a payer and consistently applies the payer ID to all test envelopes, ensuring comprehensive test coverage for the new payer-to-envelope linkage.

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

34-35: LGTM! Subscription tests properly handle payer ID.

The test setup correctly initializes and consistently applies the payer ID across all test envelopes, ensuring proper testing of the subscription functionality with the new payer-to-envelope linkage.

Also applies to: 41-41, 51-51, 62-62, 72-72, 82-82

pkg/sync/syncWorker.go (1)

465-478: LGTM! Payer ID recovery and storage logic is correct.

The method properly handles:

  1. Recovering the payer's address from the envelope
  2. Finding or creating the payer in the database
  3. Error handling for both operations
pkg/db/queries/queries.sql.go (1)

1-4: LGTM! Generated SQL code properly handles payer ID.

This is an auto-generated file by sqlc that correctly implements the database operations for the new payer_id column in the gateway_envelopes table.

Also applies to: 274-279

pkg/db/queries.sql (1)

16-17: SQL Insert Statement Update: Inclusion of payer_id
The INSERT INTO gateway_envelopes statement has been updated to include the new payer_id column alongside originator_node_id, originator_sequence_id, topic, and originator_envelope. Ensure that the application logic populates the @payer_id parameter appropriately—using a nullable type such as sql.NullInt32 will handle cases where no payer is provided.

@neekolas neekolas force-pushed the 02-21-link_payer_to_gateway_envelopes branch from 9eb284b to 635853b Compare February 21, 2025 20:29
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant