Skip to content

Conversation

@neekolas
Copy link
Contributor

@neekolas neekolas commented Apr 24, 2025

Why do this?

  • For fetching Key Packages we need to get 1 envelope per topic. The existing query API doesn't support that, and this is much more efficient than a batch query API
  • For checking which groups need to sync, we can use this as a quick check to see if any envelopes have been published since the last sync across a wide range of topics. We may want a "light mode" that skips returning the actual envelope for performance reasons, and just returns the originator_id and sequence_id of the result

Implement GetNewestEnvelope API endpoint to retrieve newest key packages for specified installation IDs

  • Adds new GetNewestEnvelope API endpoint in service.go that retrieves the newest key packages for given installation IDs
  • Implements new SQL query SelectNewestFromTopics in envelopes.sql to fetch latest envelopes by gateway time
  • Adds comprehensive test coverage in newestEnvelope_test.go
  • Updates protobuf and swagger definitions with new endpoint /mls/v2/get-newest-envelope
  • Updates various dependencies including sqlc from v1.28.0 to v1.29.0

📍Where to Start

Start with the FetchKeyPackages method implementation in service.go, which contains the main business logic for retrieving key packages.


Macroscope summarized 6704f6b.

Summary by CodeRabbit

  • New Features
    • Added the ability to retrieve the newest envelope for each specified topic.
  • Bug Fixes
    • Improved query to limit the number of staged originator envelopes returned.
  • Tests
    • Introduced comprehensive tests for retrieving the newest envelope per topic.
  • Chores
    • Upgraded multiple dependencies and code generation tools for improved compatibility and maintenance.
    • Reformatted SQL queries for consistency.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 24, 2025

Walkthrough

This change introduces a new API method, GetNewestEnvelope, to the message service, which retrieves the most recent envelope for each specified topic. Supporting this, a new SQL query and corresponding Go method, SelectNewestFromTopics, are added to efficiently fetch the newest envelopes per topic from the database. The SQL query and its generated Go code are updated accordingly. Comprehensive unit tests for the new API method are also included. Additionally, the sqlc code generation tool is updated from v1.28.0 to v1.29.0, and several indirect dependencies are bumped in the tools/go.mod file.

Changes

File(s) Change Summary
pkg/api/message/service.go Added GetNewestEnvelope method to the Service struct, implementing logic to fetch and return the newest envelope per topic using the new database query.
pkg/api/message/newestEnvelope_test.go Added comprehensive unit tests for the GetNewestEnvelope API method, including helper functions and multiple test scenarios.
pkg/db/sqlc/envelopes.sql Reformatted SQL queries for style, added LIMIT @num_rows to SelectStagedOriginatorEnvelopes, and introduced a new query SelectNewestFromTopics for retrieving the newest envelope per topic.
pkg/db/queries/envelopes.sql.go Updated for sqlc v1.29.0, reformatted code, and added new method SelectNewestFromTopics corresponding to the new SQL query.
pkg/db/queries/congestion.sql.go
pkg/db/queries/db.go
pkg/db/queries/identityUpdates.sql.go
pkg/db/queries/indexer.sql.go
pkg/db/queries/models.go
pkg/db/queries/node.sql.go
pkg/db/queries/nonceManager.sql.go
pkg/db/queries/payerReports.sql.go
Updated sqlc code generation version comment from v1.28.0 to v1.29.0. No functional changes.
tools/go.mod Updated versions of multiple indirect dependencies and removed one. No changes to direct dependencies or tooling declarations.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Service
    participant DB_Queries

    Client->>API_Service: GetNewestEnvelope(topics)
    API_Service->>DB_Queries: SelectNewestFromTopics(topics)
    DB_Queries-->>API_Service: Newest envelopes per topic
    API_Service-->>Client: GetNewestEnvelopeResponse (ordered envelopes)
Loading

Suggested reviewers

  • fbac

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 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 5d6c603 and c06c2ea.

⛔ Files ignored due to path filters (5)
  • pkg/proto/openapi/xmtpv4/message_api/message_api.swagger.json is excluded by !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api.pb.gw.go is excluded by !**/*.pb.gw.go, !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api_grpc.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • tools/go.sum is excluded by !**/*.sum
📒 Files selected for processing (13)
  • pkg/api/message/newestEnvelope_test.go (1 hunks)
  • pkg/api/message/service.go (1 hunks)
  • pkg/db/queries/congestion.sql.go (1 hunks)
  • pkg/db/queries/db.go (1 hunks)
  • pkg/db/queries/envelopes.sql.go (8 hunks)
  • pkg/db/queries/identityUpdates.sql.go (1 hunks)
  • pkg/db/queries/indexer.sql.go (1 hunks)
  • pkg/db/queries/models.go (1 hunks)
  • pkg/db/queries/node.sql.go (1 hunks)
  • pkg/db/queries/nonceManager.sql.go (1 hunks)
  • pkg/db/queries/payerReports.sql.go (1 hunks)
  • pkg/db/sqlc/envelopes.sql (1 hunks)
  • tools/go.mod (9 hunks)
✅ Files skipped from review due to trivial changes (5)
  • pkg/db/queries/nonceManager.sql.go
  • pkg/db/queries/models.go
  • pkg/db/queries/indexer.sql.go
  • pkg/db/queries/payerReports.sql.go
  • pkg/db/queries/identityUpdates.sql.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • pkg/db/queries/congestion.sql.go
  • pkg/db/queries/node.sql.go
  • pkg/db/queries/db.go
  • pkg/db/queries/envelopes.sql.go
  • pkg/api/message/service.go
  • pkg/api/message/newestEnvelope_test.go
  • pkg/db/sqlc/envelopes.sql
  • tools/go.mod
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd-cli)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd)
  • GitHub Check: Test (Node)
  • GitHub Check: Upgrade Tests
  • GitHub Check: Lint-Go
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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

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

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

🧹 Nitpick comments (3)
pkg/api/message/service.go (2)

439-440: Incorrect logger method name.

The logger context is using "GetInboxIds" method name instead of "FetchKeyPackages".

-	logger := s.log.With(zap.String("method", "GetInboxIds"))
+	logger := s.log.With(zap.String("method", "FetchKeyPackages"))

441-444: Add validation for empty installation keys.

The method doesn't check if the installationKeys slice is empty, which could lead to unnecessary database query.

	queries := queries.New(s.store)
	installationKeys := req.GetInstallationKeys()
+	if len(installationKeys) == 0 {
+		return &message_api.FetchKeyPackagesResponse{
+			OriginatorEnvelopes: []*envelopesProto.OriginatorEnvelope{},
+		}, nil
+	}
	topics := make([][]byte, len(installationKeys))
	originalSort := make(map[string]int)
pkg/api/message/keyPackages_test.go (1)

61-133: Comprehensive test for the new FetchKeyPackages API.

The test covers important scenarios: fetching multiple installation IDs, a single ID, and out-of-order IDs. It verifies both ordering preservation and that only the newest key package per installation is returned.

Consider adding test cases for error scenarios such as:

  1. Empty installation keys list
  2. Installation key with no matching key package
  3. Database query errors (could be mocked)

This would improve test coverage for error handling paths in the API method.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c8f688 and 6704f6b.

⛔ Files ignored due to path filters (7)
  • dev/gen/protos is excluded by !**/gen/**
  • pkg/proto/openapi/mls/api/v1/mls.swagger.json is excluded by !pkg/proto/**
  • pkg/proto/openapi/xmtpv4/message_api/message_api.swagger.json is excluded by !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api.pb.gw.go is excluded by !**/*.pb.gw.go, !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api_grpc.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • tools/go.sum is excluded by !**/*.sum
📒 Files selected for processing (13)
  • pkg/api/message/keyPackages_test.go (1 hunks)
  • pkg/api/message/service.go (1 hunks)
  • pkg/db/queries/congestion.sql.go (1 hunks)
  • pkg/db/queries/db.go (1 hunks)
  • pkg/db/queries/envelopes.sql.go (8 hunks)
  • pkg/db/queries/identityUpdates.sql.go (1 hunks)
  • pkg/db/queries/indexer.sql.go (1 hunks)
  • pkg/db/queries/models.go (1 hunks)
  • pkg/db/queries/node.sql.go (1 hunks)
  • pkg/db/queries/nonceManager.sql.go (1 hunks)
  • pkg/db/queries/payerReports.sql.go (1 hunks)
  • pkg/db/sqlc/envelopes.sql (1 hunks)
  • tools/go.mod (9 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pkg/db/queries/envelopes.sql.go (3)
pkg/db/queries/db.go (1)
  • Queries (23-25)
pkg/db/queries/models.go (1)
  • GatewayEnvelope (27-34)
pkg/envelopes/originator.go (1)
  • OriginatorEnvelope (13-16)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd-cli)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd)
  • GitHub Check: Upgrade Tests
  • GitHub Check: Test (Node)
  • GitHub Check: Lint-Go
  • GitHub Check: Code Review
🔇 Additional comments (26)
pkg/db/queries/nonceManager.sql.go (1)

3-3: Sqlc tool version updated to v1.29.0

The version of the sqlc code generation tool has been updated from v1.28.0 to v1.29.0. This is consistent with similar version bumps in other generated files.

pkg/db/queries/envelopes.sql.go (6)

3-3: Sqlc tool version updated to v1.29.0

The version of the sqlc code generation tool has been updated from v1.28.0 to v1.29.0, matching the version bump in other generated files.


28-32: SQL formatting changes

The SQL query has been reformatted for better readability while preserving its functionality.


63-67: SQL formatting changes

The SQL query has been reformatted for better readability while preserving its functionality.


76-93: SQL formatting changes

The SQL query has been reformatted with improved indentation and line breaks for better readability while preserving its functionality.


119-122: SQL formatting changes

The SQL query has been reformatted for better readability while preserving its functionality.


141-150: SQL formatting changes

The SQL query has been reformatted with improved indentation and line breaks for better readability while preserving its functionality.

pkg/db/sqlc/envelopes.sql (8)

1-17: SQL formatting changes

The SQL query for InsertGatewayEnvelope has been reformatted with improved indentation and line breaks for better readability while preserving its functionality.


19-27: SQL formatting changes

The SelectGatewayEnvelopes query has been reformatted for better readability while preserving its functionality.


29-31: SQL formatting changes

The InsertStagedOriginatorEnvelope query has been reformatted for better readability while preserving its functionality.


33-38: SQL formatting changes

The SelectStagedOriginatorEnvelopes query has been reformatted for better readability while preserving its functionality.


44-50: SQL formatting changes

The SelectVectorClock query has been reformatted for better readability while preserving its functionality.


52-55: SQL formatting changes

The GetLatestSequenceId query has been reformatted for better readability while preserving its functionality.


57-61: SQL formatting changes

The GetLatestCursor query has been reformatted for better readability while preserving its functionality.


63-74: New query for fetching newest envelopes by topic

This new SQL query implements the core functionality for the FetchKeyPackages API by:

  1. Using a subquery to find the maximum gateway_time for each topic in the provided list
  2. Joining this back to the gateway_envelopes table to get the complete envelope records
  3. Ordering results by topic to ensure consistent return ordering

The implementation is efficient as it uses a single query with a join rather than multiple separate queries.

pkg/db/queries/node.sql.go (1)

3-3: Sqlc tool version updated to v1.29.0

The version of the sqlc code generation tool has been updated from v1.28.0 to v1.29.0, consistent with similar version bumps in other generated files.

pkg/db/queries/db.go (1)

3-3: Update sqlc version annotation to v1.29.0.
Only the code‐generation header was bumped; no functional code was modified.

pkg/db/queries/payerReports.sql.go (1)

3-3: Update sqlc version annotation to v1.29.0.
This is an auto-generated file; no logic changes.

pkg/db/queries/congestion.sql.go (1)

3-3: Update sqlc version annotation to v1.29.0.
No functional changes aside from the tooling version bump.

pkg/db/queries/models.go (1)

3-3: Update sqlc version annotation to v1.29.0.
Generated code only; structure and types unchanged.

pkg/db/queries/identityUpdates.sql.go (1)

3-3: Update sqlc version annotation to v1.29.0.
Only metadata was updated; SQL queries and Go methods remain identical.

pkg/db/queries/indexer.sql.go (1)

3-3: Code generation version updated.

The sqlc version has been updated from v1.28.0 to v1.29.0 in the generated code comment.

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

435-439: FetchKeyPackages method implementation looks good.

The method appropriately handles the request to fetch the latest key package envelopes for specified installation keys.

tools/go.mod (1)

85-85: Dependencies updated to latest versions.

Multiple indirect dependencies have been updated, including:

  • sqlc from v1.28.0 to v1.29.0 (aligns with the generated code comment changes)
  • gRPC, protobuf, and other core dependencies
  • Various cloud provider SDKs and utility libraries

These updates keep the codebase current with the latest dependency versions.

Also applies to: 125-126, 143-143, 157-157, 162-162, 194-194, 249-250, 255-255, 285-285, 288-288, 293-293, 299-300, 316-316, 319-323, 330-331, 334-334, 339-339, 344-346, 358-358, 360-361, 363-365

pkg/api/message/keyPackages_test.go (2)

19-46: Good test helper for creating key package test data.

The writeKeyPackage helper function effectively sets up test data by creating and inserting key packages with the given installation key.


48-59: Well-structured envelope parsing helper.

The parseEnvelopes helper function makes test assertions cleaner by converting protobuf envelopes to internal envelope objects.

Comment on lines +196 to +238
const selectNewestFromTopics = `-- name: SelectNewestFromTopics :many
SELECT e.gateway_time, e.originator_node_id, e.originator_sequence_id, e.topic, e.originator_envelope, e.payer_id
FROM gateway_envelopes e
INNER JOIN (
SELECT topic,
MAX(gateway_time) AS max_time
FROM gateway_envelopes
WHERE topic = ANY($1::BYTEA [])
GROUP BY topic
) t ON e.topic = t.topic
AND e.gateway_time = t.max_time
ORDER BY e.topic
`

func (q *Queries) SelectNewestFromTopics(ctx context.Context, topics [][]byte) ([]GatewayEnvelope, error) {
rows, err := q.db.QueryContext(ctx, selectNewestFromTopics, pq.Array(topics))
if err != nil {
return nil, err
}
defer rows.Close()
var items []GatewayEnvelope
for rows.Next() {
var i GatewayEnvelope
if err := rows.Scan(
&i.GatewayTime,
&i.OriginatorNodeID,
&i.OriginatorSequenceID,
&i.Topic,
&i.OriginatorEnvelope,
&i.PayerID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 24, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

New function to retrieve newest envelopes by topic

This new query and method implementation correctly retrieves the newest gateway envelopes per topic by:

  1. Finding the maximum gateway_time for each requested topic
  2. Joining this back to the gateway_envelopes table to get the complete envelope records
  3. Ordering results by topic for consistent return order

The implementation follows the same pattern as other similar functions in this file, with proper error handling and resource cleanup.

Let's verify that no edge cases are missed:


🏁 Script executed:

#!/bin/bash
# Check if there are any existing test cases that verify behavior when topics don't exist
rg -A 5 -B 5 "SelectNewestFromTopics.*empty|no matching|not found" --type go

Length of output: 4185


Add tests for empty and non-matching topics in SelectNewestFromTopics

The new query implementation correctly retrieves the latest envelopes per topic, but there are currently no tests covering these edge cases. Please add test cases to verify that:

  • Passing an empty slice of topics returns an empty result (no error).
  • Passing topics that don’t exist in gateway_envelopes returns an empty result (no error).

Add these to your test suite (e.g. in pkg/db/queries/envelopes_test.go) to ensure consistent behavior.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is generated code

Copy link
Contributor

Choose a reason for hiding this comment

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

@neekolas You're absolutely right. I missed the "Code generated by sqlc. DO NOT EDIT" header. Since this is auto-generated code, we shouldn't modify it directly.

Looking at the PR objectives, I see you've already included test coverage in newestEnvelope_test.go. If you need to test the edge cases, those should be handled in your service-level tests rather than in the generated files.

Thanks for the correction!

@neekolas neekolas force-pushed the 04-24-add_new_fetchkeypackages_api branch from 6704f6b to 154a119 Compare April 24, 2025 15:35
@neekolas neekolas changed the title Add new FetchKeyPackages API Add GetNewestEnvelope API Endpoint Apr 24, 2025
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6704f6b and 154a119.

⛔ Files ignored due to path filters (6)
  • dev/gen/protos is excluded by !**/gen/**
  • pkg/proto/openapi/xmtpv4/message_api/message_api.swagger.json is excluded by !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api.pb.gw.go is excluded by !**/*.pb.gw.go, !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api_grpc.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • tools/go.sum is excluded by !**/*.sum
📒 Files selected for processing (13)
  • pkg/api/message/keyPackages_test.go (1 hunks)
  • pkg/api/message/service.go (1 hunks)
  • pkg/db/queries/congestion.sql.go (1 hunks)
  • pkg/db/queries/db.go (1 hunks)
  • pkg/db/queries/envelopes.sql.go (8 hunks)
  • pkg/db/queries/identityUpdates.sql.go (1 hunks)
  • pkg/db/queries/indexer.sql.go (1 hunks)
  • pkg/db/queries/models.go (1 hunks)
  • pkg/db/queries/node.sql.go (1 hunks)
  • pkg/db/queries/nonceManager.sql.go (1 hunks)
  • pkg/db/queries/payerReports.sql.go (1 hunks)
  • pkg/db/sqlc/envelopes.sql (1 hunks)
  • tools/go.mod (9 hunks)
✅ Files skipped from review due to trivial changes (7)
  • pkg/db/queries/node.sql.go
  • pkg/db/queries/payerReports.sql.go
  • pkg/db/queries/db.go
  • pkg/db/queries/indexer.sql.go
  • pkg/db/queries/nonceManager.sql.go
  • pkg/db/queries/models.go
  • pkg/db/queries/identityUpdates.sql.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • pkg/db/queries/congestion.sql.go
  • pkg/db/queries/envelopes.sql.go
  • pkg/api/message/service.go
  • pkg/db/sqlc/envelopes.sql
  • tools/go.mod
🧰 Additional context used
🪛 GitHub Check: Lint-Go
pkg/api/message/keyPackages_test.go

[failure] 147-147:
File is not properly formatted (gofumpt)

🪛 GitHub Actions: Lint
pkg/api/message/keyPackages_test.go

[error] 147-147: File is not properly formatted (gofumpt)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd-cli)
  • GitHub Check: Test (Node)
  • GitHub Check: Upgrade Tests
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd)
  • GitHub Check: Code Review
🔇 Additional comments (6)
pkg/api/message/keyPackages_test.go (6)

1-17: LGTM! Well-structured imports.

The package is correctly defined as message_test for black-box testing, and imports are organized appropriately.


19-46: LGTM! Well-implemented helper function.

The writeKeyPackage helper encapsulates all the necessary steps to create and insert a test key package envelope. Good use of the testutils package for random generation.


48-62: LGTM! Robust envelope parsing.

The parseEnvelopes helper correctly handles nil envelopes and converts the protobuf format to internal envelope objects.


64-85: LGTM! Clear test setup.

Good test setup with multiple installation IDs and creation of multiple key packages for installation ID 1 to verify that only the newest is returned.


86-123: LGTM! Comprehensive test cases.

Well-designed test cases covering multiple scenarios:

  • Fetching multiple installation IDs
  • Single ID fetching
  • Order independence
  • Handling missing envelopes

The expected values are clearly defined for each test case.


125-159: LGTM! Thorough verification logic.

The test execution and verification are comprehensive, checking both the topics and sequence IDs of the returned envelopes. Good handling of nil values in the verification stage.

🧰 Tools
🪛 GitHub Check: Lint-Go

[failure] 147-147:
File is not properly formatted (gofumpt)

🪛 GitHub Actions: Lint

[error] 147-147: File is not properly formatted (gofumpt)

@neekolas neekolas force-pushed the 04-24-add_new_fetchkeypackages_api branch from 154a119 to 4ae0630 Compare April 24, 2025 15:39
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

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

97-101: Consider adding test case with empty topics array

While the current test cases are comprehensive, it might be worth adding a test case for an empty topics array to ensure the API handles this edge case gracefully.

		{
			name: "all three installation IDs",
			requestedTopics: []topic.Topic{
				topic1, topic2, topic3,
			},
			expectedNumReturned: 3,
			expectedTopics:      []*topic.Topic{&topic1, &topic2, &topic3},
			expectedSequenceIDs: []uint64{seq1, seq2, seq3},
		},
+		{
+			name:                "empty topics array",
+			requestedTopics:     []topic.Topic{},
+			expectedNumReturned: 0,
+			expectedTopics:      []*topic.Topic{},
+			expectedSequenceIDs: []uint64{},
+		},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 154a119 and 4ae0630.

⛔ Files ignored due to path filters (6)
  • dev/gen/protos is excluded by !**/gen/**
  • pkg/proto/openapi/xmtpv4/message_api/message_api.swagger.json is excluded by !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api.pb.gw.go is excluded by !**/*.pb.gw.go, !pkg/proto/**
  • pkg/proto/xmtpv4/message_api/message_api_grpc.pb.go is excluded by !**/*.pb.go, !pkg/proto/**
  • tools/go.sum is excluded by !**/*.sum
📒 Files selected for processing (13)
  • pkg/api/message/newestEnvelope_test.go (1 hunks)
  • pkg/api/message/service.go (1 hunks)
  • pkg/db/queries/congestion.sql.go (1 hunks)
  • pkg/db/queries/db.go (1 hunks)
  • pkg/db/queries/envelopes.sql.go (8 hunks)
  • pkg/db/queries/identityUpdates.sql.go (1 hunks)
  • pkg/db/queries/indexer.sql.go (1 hunks)
  • pkg/db/queries/models.go (1 hunks)
  • pkg/db/queries/node.sql.go (1 hunks)
  • pkg/db/queries/nonceManager.sql.go (1 hunks)
  • pkg/db/queries/payerReports.sql.go (1 hunks)
  • pkg/db/sqlc/envelopes.sql (1 hunks)
  • tools/go.mod (9 hunks)
✅ Files skipped from review due to trivial changes (6)
  • pkg/db/queries/db.go
  • pkg/db/queries/identityUpdates.sql.go
  • pkg/db/queries/models.go
  • pkg/db/queries/node.sql.go
  • pkg/db/queries/payerReports.sql.go
  • pkg/db/queries/indexer.sql.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • pkg/db/queries/nonceManager.sql.go
  • pkg/db/queries/congestion.sql.go
  • pkg/api/message/service.go
  • pkg/db/queries/envelopes.sql.go
  • tools/go.mod
  • pkg/db/sqlc/envelopes.sql
🧰 Additional context used
🪛 GitHub Check: Lint-Go
pkg/api/message/newestEnvelope_test.go

[failure] 147-147:
File is not properly formatted (gofumpt)

🪛 GitHub Actions: Lint
pkg/api/message/newestEnvelope_test.go

[error] 147-147: File is not properly formatted (gofumpt)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd-cli)
  • GitHub Check: Upgrade Tests
  • GitHub Check: Test (Node)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd)
🔇 Additional comments (2)
pkg/api/message/newestEnvelope_test.go (2)

1-159: Excellent test coverage for the new API endpoint

The test file provides comprehensive coverage for the GetNewestEnvelope API endpoint with well-structured helper functions and thorough test cases. The tests cover multiple scenarios including:

  • Multiple installation IDs
  • Single installation ID queries
  • Out-of-order topic requests
  • Topics with no existing envelopes

The helper functions writeKeyPackage and parseEnvelopes are well-designed to support the tests and make the code more readable.

🧰 Tools
🪛 GitHub Check: Lint-Go

[failure] 147-147:
File is not properly formatted (gofumpt)

🪛 GitHub Actions: Lint

[error] 147-147: File is not properly formatted (gofumpt)


19-46:

Details

✅ Verification successful

Verify database isolation between test runs

The writeKeyPackage function uses a fixed nodeID (100) for all entries. While this works for the current tests, it could potentially cause issues if tests are run in parallel or if the database isn't properly cleaned between test runs.


🏁 Script executed:

#!/bin/bash
# Check if there are test isolation mechanisms in place
grep -r "t.Parallel()" pkg/api/message/*_test.go
grep -r "cleanup" pkg/testutils/api/api.go

Length of output: 172


I’ll inspect the test setup to see how the database is provisioned and whether each test gets its own isolated instance or cleanup logic.


🏁 Script executed:

#!/bin/bash
# Show the top of the message tests to find any setup/teardown or DB initialization
sed -n '1,200p' pkg/api/message/newestEnvelope_test.go

# Show the test utils API helper to spot any DB cleanup or per-test DB creation
sed -n '1,200p' pkg/testutils/api/api.go

Length of output: 10207


Let’s locate the definition of NewTestReplicationAPIClient and inspect how testutils.NewDB sets up and tears down the database:


🏁 Script executed:

#!/bin/bash
# Find the test API client initializer
grep -R "NewTestReplicationAPIClient" -n pkg/testutils/api/api.go

# Inspect how the test DB is created and cleaned up
grep -R "func NewDB" -n pkg/testutils

Length of output: 349


Database isolation confirmed; fixed NodeID is safe

The NewTestReplicationAPIClient helper calls testutils.NewDB, which creates a fresh database instance for each top-level test and registers its cleanup via t.Cleanup. Additionally, no tests in pkg/api/message use t.Parallel(). As a result, each invocation of TestGetNewestEnvelope runs against its own isolated database, and the hard-coded nodeID = 100 cannot conflict across tests.

@neekolas neekolas force-pushed the 04-24-add_new_fetchkeypackages_api branch 5 times, most recently from a6f8d2c to 5d6c603 Compare April 24, 2025 18:39
@neekolas neekolas marked this pull request as ready for review April 24, 2025 18:40
@neekolas neekolas requested a review from a team as a code owner April 24, 2025 18:40
@macroscopeapp
Copy link

macroscopeapp bot commented Apr 24, 2025

Add GetNewestEnvelope API endpoint to retrieve the most recent envelope for requested topics

  • Implements new GetNewestEnvelope API endpoint in service.go that retrieves the newest envelope for each requested topic while preserving topic order
  • Adds new SQL query and function SelectNewestFromTopics in envelopes.sql.go to fetch the most recent envelope per topic
  • Creates comprehensive test coverage in newestEnvelope_test.go for various scenarios
  • Adds OpenAPI definitions and generated protobuf/gRPC code for the new endpoint
  • Updates various dependencies including sqlc from v1.28.0 to v1.29.0

📍Where to Start

Start with the GetNewestEnvelope method in service.go which implements the main API endpoint logic.


Macroscope summarized c06c2ea.

@neekolas neekolas force-pushed the 04-24-add_new_fetchkeypackages_api branch from 5d6c603 to a75465d Compare April 24, 2025 18:47
@neekolas neekolas force-pushed the 04-24-add_new_fetchkeypackages_api branch from a75465d to c06c2ea Compare April 25, 2025 14:55
@neekolas neekolas merged commit 7f034a1 into main Apr 25, 2025
9 checks passed
@neekolas neekolas deleted the 04-24-add_new_fetchkeypackages_api branch April 25, 2025 21:44
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.

3 participants