Skip to content

Conversation

@mkysel
Copy link
Collaborator

@mkysel mkysel commented May 8, 2025

Add scaffolding for XMTPD database pruning by implementing prune command-line tool, configuration, and Docker support

  • Implements new xmtpd-prune command-line tool in main.go with configuration and database connection handling
  • Adds Docker build support through Dockerfile-prune and updated build-xmtpd.yml workflow
  • Creates database connection utilities in pgx.go with configurable timeouts and namespace support
  • Establishes configuration structures and validation in pruneOptions.go and validation.go
  • Sets up placeholder pruning executor in prune.go for future implementation

📍Where to Start

Start with the main entry point in main.go which sets up the command-line interface, configuration parsing, and execution flow for the pruning tool.


Macroscope summarized 6566e91.

Summary by CodeRabbit

  • New Features

    • Introduced a new command-line tool for database pruning operations.
    • Added a Docker image variant for the pruning tool, now available alongside existing images.
    • Provided a Bash script to simplify local development and execution of the pruning tool.
  • Documentation

    • Updated workflow to build and publish the new pruning tool Docker image.

@mkysel mkysel requested a review from a team as a code owner May 8, 2025 15:39
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 8, 2025

Walkthrough

A new "prune" command-line tool and supporting infrastructure were added, including its Go implementation, configuration, validation, Docker packaging, and development script. The build workflow was updated to build and push the new "xmtpd-prune" Docker image. Supporting code for database connection and a stub executor for pruning were also introduced.

Changes

File(s) Change Summary
.github/workflows/build-xmtpd.yml Updated build workflow to include "xmtpd-prune" image in the build/push matrix and Dockerfile selection logic.
dev/docker/Dockerfile-prune Added Dockerfile to build and package the new "xmtpd-prune" Go application using a multi-stage build.
dev/prune New Bash script to build and run the prune tool with embedded version info, sourcing environment variables.
cmd/prune/main.go Added main entry point for the prune tool: parses options, validates, logs, connects to DB, and invokes prune executor.
pkg/prune/prune.go Introduced Executor struct and methods as scaffolding for the prune operation logic.
pkg/config/pruneOptions.go Added PruneOptions struct to group database and logging configuration for the prune tool.
pkg/config/validation.go Added ValidatePruneOptions function to check required prune configuration options.
pkg/db/pgx.go Added ConnectToDB function for establishing a DB connection without running migrations or creating namespaces.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PruneCLI as Prune CLI (main.go)
    participant Config as Config/Validation
    participant Logger
    participant DB as Database Connector
    participant Executor as Prune Executor

    User->>PruneCLI: Run prune command with options
    PruneCLI->>Config: Parse and validate PruneOptions
    Config-->>PruneCLI: Return validation result
    PruneCLI->>Logger: Initialize logger
    PruneCLI->>DB: ConnectToDB with options
    DB-->>PruneCLI: Return DB handle
    PruneCLI->>Executor: NewPruneExecutor(ctx, logger, db)
    PruneCLI->>Executor: Run()
    Executor-->>PruneCLI: Return result
    PruneCLI-->>User: Exit (success or error)
Loading

Possibly related PRs

  • Build the correct image #308: Extended Dockerfile selection logic in the GitHub Actions workflow to support the new "xmtpd-prune" image variant.

Suggested reviewers

  • neekolas
  • fbac

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 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 6566e91 and 469ad0f.

📒 Files selected for processing (2)
  • pkg/config/validation.go (1 hunks)
  • pkg/db/pgx.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/config/validation.go
  • pkg/db/pgx.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • 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
✨ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

@graphite-app
Copy link

graphite-app bot commented May 8, 2025

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • Queue - adds this PR to the back of the merge queue
  • Hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

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

🧹 Nitpick comments (6)
pkg/db/pgx.go (2)

161-166: Consider improving function signature readability

The parameter arrangement in this function signature is slightly inconsistent. The waitForDB and statementTimeout parameters are on the same line, while namespace is on the same line without a line-breaking comma.

Consider rearranging the parameters to improve readability:

func ConnectToDB(
	ctx context.Context,
	logger *zap.Logger,
	dsn string,
-	waitForDB time.Duration, statementTimeout time.Duration, namespace string,
+	waitForDB time.Duration, 
+	statementTimeout time.Duration, 
+	namespace string,
) (*sql.DB, error) {

172-174: Consider validating the namespace if provided

While the function allows for an optional namespace, it doesn't validate it when provided, unlike the createNamespace function which calls isValidNamespace.

Add validation to ensure the provided namespace is valid:

if namespace != "" {
+	if err := isValidNamespace(namespace); err != nil {
+		return nil, err
+	}
	config.ConnConfig.Database = namespace
}
dev/prune (1)

1-7: Add checks for prerequisites and error handling

This script assumes that the dev/local.env file exists and that git is correctly configured with tags. While set -eu helps with error detection, more explicit checks could improve the user experience.

Consider adding checks for the environment file and providing fallback for version information:

#!/bin/bash

set -eu

+# Check if local.env exists
+if [ ! -f dev/local.env ]; then
+  echo "Error: dev/local.env not found. Please create it before running this script."
+  exit 1
+fi

. dev/local.env

+# Get version with fallback
+VERSION=$(git describe HEAD --tags --long 2>/dev/null || echo "unknown")
+
-go run -ldflags="-X main.Version=$(git describe HEAD --tags --long)" cmd/prune/main.go "$@"
+go run -ldflags="-X main.Version=$VERSION" cmd/prune/main.go "$@"
dev/docker/Dockerfile-prune (1)

1-35: Well-structured Dockerfile following best practices

The multi-stage build approach effectively minimizes the final image size while properly configuring the environment for the pruning tool.

Consider providing a default value for the VERSION build arg to match the "unknown" fallback used in the build command:

-ARG VERSION=unknown
+ARG VERSION=unknown
cmd/prune/main.go (2)

29-34: Consider a fallback version instead of failing

Instead of failing when Version is not set by build or environment, consider providing a fallback value to improve robustness.

 if Version == "" {
 	Version = os.Getenv("VERSION")
 	if Version == "" {
-		fatal("Could not determine version")
+		Version = "development"
+		logger.Warn("Could not determine version, using default", zap.String("version", Version))
 	}
 }

69-71: Consider using structured logging for fatal errors

The current implementation uses standard log.Fatalf, but using the structured logger would provide consistency with the rest of the application's logging.

 func fatal(msg string, args ...any) {
-	log.Fatalf(msg, args...)
+	if logger != nil {
+		logger.Fatal(fmt.Sprintf(msg, args...))
+	} else {
+		log.Fatalf(msg, args...)
+	}
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ff91ac7 and 6566e91.

📒 Files selected for processing (8)
  • .github/workflows/build-xmtpd.yml (2 hunks)
  • cmd/prune/main.go (1 hunks)
  • dev/docker/Dockerfile-prune (1 hunks)
  • dev/prune (1 hunks)
  • pkg/config/pruneOptions.go (1 hunks)
  • pkg/config/validation.go (1 hunks)
  • pkg/db/pgx.go (1 hunks)
  • pkg/prune/prune.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
pkg/config/validation.go (2)
pkg/config/pruneOptions.go (1)
  • PruneOptions (3-6)
pkg/db/queries/db.go (1)
  • New (19-21)
pkg/config/pruneOptions.go (1)
pkg/config/options.go (2)
  • DbOptions (24-32)
  • LogOptions (73-76)
cmd/prune/main.go (5)
pkg/config/pruneOptions.go (1)
  • PruneOptions (3-6)
pkg/config/validation.go (1)
  • ValidatePruneOptions (95-125)
pkg/utils/log.go (1)
  • BuildLogger (9-40)
pkg/db/pgx.go (1)
  • ConnectToDB (161-184)
pkg/prune/prune.go (1)
  • NewPruneExecutor (16-26)
🔇 Additional comments (5)
.github/workflows/build-xmtpd.yml (2)

55-56: LGTM: Good addition for the new prune image

The conditional logic to select the appropriate Dockerfile for the "xmtpd-prune" image is well-integrated with the existing pattern.


15-15:

Details

✅ Verification successful

Confirm that the Dockerfile-prune exists and functions properly

The addition of "xmtpd-prune" to the matrix strategy assumes that there's a corresponding Dockerfile-prune in ./dev/docker/ directory.

Verify that the Dockerfile exists and contains the proper configuration:


🏁 Script executed:

#!/bin/bash
# Check if Dockerfile-prune exists
if [ -f ./dev/docker/Dockerfile-prune ]; then
  echo "Dockerfile-prune exists:"
  echo "----------------------"
  cat ./dev/docker/Dockerfile-prune | head -10
  echo "..."
else
  echo "ERROR: Dockerfile-prune not found in ./dev/docker/"
fi

Length of output: 467


🏁 Script executed:

#!/bin/bash
echo "ENTRYPOINT/CMD lines in dev/docker/Dockerfile-prune:"
rg "(ENTRYPOINT|CMD)" -n dev/docker/Dockerfile-prune || true

echo ""
echo "---- Last 20 lines of dev/docker/Dockerfile-prune ----"
tail -n 20 dev/docker/Dockerfile-prune

Length of output: 862


Dockerfile-prune exists and is correctly configured

  • Confirmed dev/docker/Dockerfile-prune is present.
  • Includes a two-stage build (builder and alpine:3.21) and sets
    ENTRYPOINT ["/usr/bin/xmtpd-prune"] as expected.
pkg/config/validation.go (1)

95-125: LGTM - Clean implementation of ValidatePruneOptions

The validation function correctly checks for the required DB.WriterConnectionString field and follows the established pattern from ValidateServerOptions.

pkg/prune/prune.go (1)

1-31: Good foundation for the pruning executor

The Executor struct is well-designed with proper encapsulation of dependencies (context, logger, and database connection). The structure provides a clean starting point for implementing the actual pruning logic in future PRs.

Note that the Run method is currently just a placeholder. In future PRs, this will need to be implemented with the actual pruning logic, including data retention policies, transaction management, and error handling.

cmd/prune/main.go (1)

1-68: Well-orchestrated command-line tool implementation

The main package effectively coordinates configuration parsing, validation, database connection setup, and pruning execution with proper error handling at each step.

Consider adding graceful shutdown handling in a future PR to ensure proper cleanup of resources (especially database connections) when the process is terminated.

#!/bin/bash
# Check for other database connection management in the codebase
# to ensure consistency with existing patterns

# Search for signal handling patterns
rg -A 5 "os.Signal|signal.Notify" --type go

@macroscopeapp
Copy link

macroscopeapp bot commented May 8, 2025

Add database pruning infrastructure to XMTPD by implementing xmtpd-prune command-line tool and Docker container

Implements the foundational components for database pruning in XMTPD:

  • Adds new xmtpd-prune command-line tool in main.go with configuration validation and database connectivity
  • Creates Docker build infrastructure with Dockerfile-prune and CI/CD workflow updates in build-xmtpd.yml
  • Implements database connection handling in pgx.go with new ConnectToDB function for existing database connections
  • Establishes pruning configuration structure in pruneOptions.go with validation logic
  • Adds development convenience script dev/prune for local testing

📍Where to Start

Start with the main entry point in main.go which sets up the pruning tool's core functionality and demonstrates the overall flow from configuration to execution.

Changes since #772 opened

  • Removed unused validation functionality from config.ValidatePruneOptions [469ad0f]
  • Streamlined error handling in config.ValidatePruneOptions [469ad0f]

Macroscope summarized 469ad0f.


func ValidatePruneOptions(options PruneOptions) error {
missingSet := make(map[string]struct{})
customSet := make(map[string]struct{})
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do you plan on using customSet? Otherwise it can be deleted.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I shall delete

@mkysel mkysel merged commit bf804cf into main May 8, 2025
10 checks passed
@mkysel mkysel deleted the mkysel/xmtpd-prune branch May 8, 2025 18: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.

3 participants