Skip to content

Conversation

@fracek
Copy link
Contributor

@fracek fracek commented Mar 21, 2025

The MongoDB had the following issues:

  • calling createCollection on an already existing collection returns an error.
  • withTransaction defaults to retrying by invoking the callback multiple times, but this is unacceptable for the middleware.

This PR fixes both issues.

@coderabbitai
Copy link

coderabbitai bot commented Mar 21, 2025

📝 Walkthrough

Walkthrough

This pull request simplifies and expands the build, test, and release workflows by removing directory exclusion filters. It introduces new files for MongoDB support including configuration, Docker Compose, and an indexer for Starknet. Additionally, the update removes specific apibara-related scripts from several CLI examples. In the plugin-mongo package, collection handling is modified to retrieve existing collections and the transaction process is updated with a new option disabling retryable writes. A new JSON file marks a prerelease addressing a connection issue for the @apibara/plugin-mongo package.

Changes

File(s) Change Summary
.github/workflows/build.yml, .github/workflows/release.yml Removed filters excluding specific directories from build and test commands to simplify workflows.
change/@apibara-plugin-mongo-*.json Added a new JSON file marking a prerelease for @apibara/plugin-mongo, addressing connection errors and disabling retry mechanism.
examples/cli-drizzle/package.json, examples/cli-instrumentation/package.json, examples/cli-js/package.json Removed apibara-specific scripts (build, start, and for drizzle also start:pg) from the package scripts.
examples/cli-mongodb/apibara.config.mjs, docker-compose.yaml, indexers/starknet.indexer.js, package.json Introduced new files for the MongoDB example setup including configuration, Docker Compose for MongoDB, a Starknet indexer, and package metadata.
packages/plugin-mongo/src/persistence.ts, packages/plugin-mongo/src/utils.ts Modified persistence to use existing MongoDB collections instead of creating them, and updated transaction handling by adding an option to disable retryable writes.

Sequence Diagram(s)

sequenceDiagram
    participant GitHub Actions
    participant Build Command
    participant Test Command
    GitHub Actions->>Build Command: Trigger build (pnpm build)
    Build Command->>Test Command: Trigger test (pnpm test:ci)
Loading
sequenceDiagram
    participant Starknet Indexer
    participant Blockchain
    participant Logger
    participant MongoDB
    Starknet Indexer->>Blockchain: Connect to event stream
    Blockchain-->>Starknet Indexer: Send block data
    Starknet Indexer->>Logger: Log block header & transaction insertion
    Starknet Indexer->>MongoDB: Insert blocks and transactions
Loading

Possibly related PRs

Poem

I'm a rabbit in the code, leaping without a care,
Workflows now run freely, with exclusions nowhere.
MongoDB setups and indexers join my joyful play,
Scripts removed for simplicity, leading the way.
With hops and gentle code, I celebrate this day! 🐰
Happy coding, friends, in our bright new display!

✨ 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 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: 1

🧹 Nitpick comments (2)
examples/cli-mongodb/indexers/starknet.indexer.js (2)

8-8: Consider externalizing MongoDB connection string.

The MongoDB connection string contains hardcoded credentials. While this may be acceptable for an example, it would be better to use environment variables for the connection details.

- const mongodb = new MongoClient("mongodb://mongo:mongo@localhost:27017/");
+ const mongoUri = process.env.MONGODB_URI || "mongodb://mongo:mongo@localhost:27017/";
+ const mongodb = new MongoClient(mongoUri);

24-32: Transform function looks good but could handle errors better.

The transform function properly inserts data into MongoDB, but it lacks error handling. Consider adding try/catch blocks to handle potential database errors gracefully.

 async transform({ block: { header, transactions } }) {
   const logger = useLogger();
   const mongo = useMongoStorage();

+  try {
     await mongo.collection("blocks").insertOne(header);
     await mongo.collection("transactions").insertMany(transactions);

     logger.info(`Inserted block ${header.blockNumber}`);
+  } catch (error) {
+    logger.error(`Error processing block ${header.blockNumber}: ${error.message}`);
+    throw error; // Re-throw to let the indexer framework handle it
+  }
 },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5002c59 and 59210c1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (12)
  • .github/workflows/build.yml (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • change/@apibara-plugin-mongo-8a313e7a-5b45-4ae6-9727-2fa720b6f46c.json (1 hunks)
  • examples/cli-drizzle/package.json (0 hunks)
  • examples/cli-instrumentation/package.json (1 hunks)
  • examples/cli-js/package.json (0 hunks)
  • examples/cli-mongodb/apibara.config.mjs (1 hunks)
  • examples/cli-mongodb/docker-compose.yaml (1 hunks)
  • examples/cli-mongodb/indexers/starknet.indexer.js (1 hunks)
  • examples/cli-mongodb/package.json (1 hunks)
  • packages/plugin-mongo/src/persistence.ts (1 hunks)
  • packages/plugin-mongo/src/utils.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • examples/cli-js/package.json
  • examples/cli-drizzle/package.json
🔇 Additional comments (9)
examples/cli-mongodb/apibara.config.mjs (1)

1-3: Clean and minimal configuration setup

This is a simple and effective configuration file that provides a basic template for MongoDB integration with Apibara. The empty configuration is a good starting point that can be expanded as needed.

change/@apibara-plugin-mongo-8a313e7a-5b45-4ae6-9727-2fa720b6f46c.json (1)

1-7: Appropriate change file documenting the PR fixes

This change file correctly documents the purpose of this PR - fixing connection errors and disabling retry functionality. The metadata is complete with package name, email, and the appropriate dependent change type.

packages/plugin-mongo/src/persistence.ts (1)

25-26: Good fix for the collection creation error

Changing from createCollection to collection effectively addresses the error that occurs when trying to create collections that already exist during restart. This method retrieves the collection reference without attempting to create it, allowing the application to restart smoothly while maintaining the existing collections.

examples/cli-mongodb/docker-compose.yaml (1)

1-20: MongoDB setup looks good with proper replica set configuration.

The Docker Compose configuration properly sets up MongoDB with a replica set, which is necessary for transaction support. The configuration includes proper volume mounting for data persistence and appropriate environment variables for initialization.

examples/cli-instrumentation/package.json (1)

7-11: Removal of build and start scripts appears intentional.

The build and start scripts have been removed from the package.json file. This matches the PR's simplification of the build workflow and aligns with similar changes in other example files.

.github/workflows/build.yml (1)

46-51: Build workflow simplification looks good.

The removal of directory exclusion filters from the build and test commands simplifies the workflow and ensures all directories are included in the build and test processes. This change aligns with the PR objective of improving the build process.

examples/cli-mongodb/indexers/starknet.indexer.js (1)

1-34: Note about the core PR objectives.

This example file demonstrates the usage of the MongoDB plugin, but I don't see the core fixes mentioned in the PR description (handling collection creation errors and transaction retry behavior). These fixes likely exist in the @apibara/plugin-mongo package itself rather than this example.

packages/plugin-mongo/src/utils.ts (1)

15-22:

✅ Verification successful

Transaction retry behavior fixed

Adding the retryWrites: false option to the session.withTransaction call properly addresses one of the PR objectives - preventing automatic transaction retries by MongoDB. This change is important because automatic retries can cause unexpected behavior when used with custom middleware.


🏁 Script executed:

#!/bin/bash
# Check MongoDB documentation on transactions and retryWrites option
curl -s 'https://mongodb.github.io/node-mongodb-native/5.0/interfaces/TransactionOptions.html' | grep -A 5 retryWrites

Length of output: 21339


Verified: Transaction retry behavior is correctly disabled

The code now explicitly passes retryWrites: false to session.withTransaction, ensuring that automatic retries are disabled. This aligns with the PR’s objective and is consistent with the MongoDB documentation, which indicates that the default behavior is to retry writes unless this option is overridden.

  • Location: packages/plugin-mongo/src/utils.ts (Lines 15-22)
  • Rationale: Disabling automatic transaction retries prevents potential unexpected behavior when using custom middleware.
examples/cli-mongodb/package.json (1)

1-26: New MongoDB example configuration looks good

The package.json for the new MongoDB CLI example is well-structured with appropriate dependencies. This example will be useful for demonstrating the fixes implemented in this PR.

A few observations:

  • Using MongoDB v6.12.0, which is recent and compatible with the plugin changes
  • All Apibara dependencies use workspace references for local development
  • Includes proper linting configuration with Biome

Copy link
Member

@jaipaljadeja jaipaljadeja left a comment

Choose a reason for hiding this comment

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

LGTM! Thanks

@jaipaljadeja jaipaljadeja merged commit 0c31a34 into apibara:main Mar 21, 2025
2 checks passed
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