Skip to content

Conversation

@smypmsa
Copy link
Member

@smypmsa smypmsa commented Aug 9, 2025

Summary by CodeRabbit

  • Refactor
    • Updated naming conventions for constants to improve consistency across the application.
    • Changed region-based metric availability to use a list of allowed regions rather than a single region.
    • Metrics are now only available in specific deployment regions, as determined by environment variables.
    • Improved maintainability by generalizing region checks for metric collection.

@vercel
Copy link

vercel bot commented Aug 9, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
chainstack-rpc-dashboard-germany ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 9, 2025 0:13am
chainstack-rpc-dashboard-singapore ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 9, 2025 0:13am
chainstack-rpc-dashboard-us-west ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 9, 2025 0:13am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 9, 2025

Walkthrough

The changes introduce environment-based gating for metric collection across several blockchain-related API modules. Each affected file now imports os, defines an ALLOWED_REGIONS list, and conditionally assigns the METRICS constant based on whether the VERCEL_REGION environment variable is present in this list. Metric name constants are also standardized to uppercase.

Changes

Cohort / File(s) Change Summary
Read API region-gated metrics
api/read/arbitrum.py, api/read/base.py, api/read/bnbsc.py, api/read/ethereum.py, api/read/solana.py, api/read/test_blockchain.py, api/read/ton.py
Added os import and ALLOWED_REGIONS list; renamed metric_name to METRIC_NAME; updated METRICS to be conditionally defined based on VERCEL_REGION environment variable; updated handler classes to use the new METRICS logic.
Write API region gating
api/write/solana.py
Refactored metric_name to METRIC_NAME and target_region to ALLOWED_REGIONS (list); generalized conditional logic for METRICS to check membership in ALLOWED_REGIONS instead of equality; updated comments for clarity.

Sequence Diagram(s)

sequenceDiagram
    participant Environment
    participant Module
    participant Handler

    Environment->>Module: Set VERCEL_REGION
    Module->>Module: Check if VERCEL_REGION in ALLOWED_REGIONS
    alt Region allowed
        Module->>Handler: Assign METRICS = full metric list
    else Region not allowed
        Module->>Handler: Assign METRICS = []
    end
    Handler->>Client: Serve metrics (if available)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Possibly related PRs

Poem

In regions allowed, the metrics hop,
But outside their bounds, they quietly stop.
With uppercase names and logic refined,
Only the right regions will metrics find.
A rabbit approves with a metric cheer—
Region-gated code is finally here! 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

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 generate unit tests to generate unit tests 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.

@smypmsa smypmsa merged commit 41f21d7 into master Aug 9, 2025
4 of 5 checks passed
@smypmsa smypmsa deleted the dev branch August 9, 2025 12:17
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

♻️ Duplicate comments (3)
api/read/test_blockchain.py (1)

13-18: Same duplication as noted in solana.py – see earlier comment about centralising ALLOWED_REGIONS.

api/read/ton.py (1)

29-30: VERCEL_REGION case-insensitive check – same note as previous files.

api/read/ethereum.py (1)

17-23: Duplicate constant & potential drift

See earlier advice on centralising ALLOWED_REGIONS; keeping one source avoids mismatched lists across chains.

🧹 Nitpick comments (12)
api/read/solana.py (2)

15-20: Centralise ALLOWED_REGIONS to avoid drift

Each blockchain module now hard-codes the same region list. Moving this constant to a shared place (e.g. config.defaults) or a helper like get_allowed_regions() keeps the list in sync and eliminates five-way duplication.


22-33: Guard for case / missing env & make lookup O(1)

os.getenv("VERCEL_REGION") may return None or an upper-case code ("FRA1").
Small tweaks improve robustness and micro-perf:

-ALLOWED_REGIONS: list[str] = [...]
+ALLOWED_REGIONS: frozenset[str] = {...}

-region = os.getenv("VERCEL_REGION")
-if region in ALLOWED_REGIONS:
+region = (os.getenv("VERCEL_REGION") or "").lower()
+if region in ALLOWED_REGIONS:
api/read/test_blockchain.py (1)

27-28: Normalise env var case

As above, consider .lower() on the fetched region to avoid silent metric drop-outs in mixed-case deployments.

api/read/ton.py (1)

15-20: Consider making ALLOWED_REGIONS a frozenset

Immutability conveys intent (config, not data) and speeds membership checks.

api/read/ethereum.py (1)

35-36: Minor: evaluate at runtime, not import-time

If you ever hot-reload or change env vars between requests, compute the region inside the handler constructor instead of at module import so the decision reflects current env.

api/read/bnbsc.py (3)

1-1: Prefer a module docstring over per-line noqa for D100

Add a minimal module docstring and drop the inline # noqa: D100 to satisfy pydocstyle cleanly.

Apply:

-import os  # noqa: D100
+"""BNB Smart Chain metrics read handler."""
+import os

18-24: ALLOWED_REGIONS consistency and centralization

This per-file allowlist can drift across modules. Consider centralizing allowed regions (per-chain or global) in config (e.g., config.defaults) or an env var, and document the rationale for each region.


18-24: Use an immutable set for membership checks

Tiny nit: use a frozenset for clarity and O(1) membership.

-ALLOWED_REGIONS: list[str] = [
+ALLOWED_REGIONS: frozenset[str] = frozenset({
     "fra1",  # Frankfurt (EU)
     "sfo1",  # San Francisco (US West)
     "sin1",  # Singapore
     # "kix1",  # Osaka (JP)
-]
+})
api/read/arbitrum.py (2)

1-1: Prefer a module docstring over per-line noqa for D100

Same nit as other modules: add a brief module docstring and remove inline # noqa: D100.

-import os  # noqa: D100
+"""Arbitrum metrics read handler."""
+import os

18-24: Allowed regions differ from bnbsc (sin1 commented here, kix1 enabled there)

If this divergence is intentional (provider availability, latency, cost), please add a short comment linking to the decision source, or centralize per-chain allowlists in config to avoid drift.

api/write/solana.py (2)

1-1: Prefer a module docstring over per-line noqa for D100

Add a minimal docstring and remove the inline noqa.

-import os  # noqa: D100
+"""Solana write metrics handler."""
+import os

7-8: Type/structure ALLOWED_REGIONS consistently

For consistency with other modules and to avoid accidental mutation, consider a typed, immutable allowlist.

-METRIC_NAME = f"{MetricsServiceConfig.METRIC_PREFIX}transaction_landing_latency"
-ALLOWED_REGIONS = ["fra1"]
+METRIC_NAME = f"{MetricsServiceConfig.METRIC_PREFIX}transaction_landing_latency"
+ALLOWED_REGIONS: tuple[str, ...] = ("fra1",)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d4ce7a6 and 0a37097.

📒 Files selected for processing (8)
  • api/read/arbitrum.py (2 hunks)
  • api/read/base.py (2 hunks)
  • api/read/bnbsc.py (2 hunks)
  • api/read/ethereum.py (2 hunks)
  • api/read/solana.py (2 hunks)
  • api/read/test_blockchain.py (2 hunks)
  • api/read/ton.py (2 hunks)
  • api/write/solana.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
api/read/test_blockchain.py (2)
config/defaults.py (1)
  • MetricsServiceConfig (6-42)
metrics/solana.py (4)
  • HTTPGetRecentBlockhashLatencyMetric (23-33)
  • HTTPSimulateTxLatencyMetric (6-20)
  • HTTPGetBalanceLatencyMetric (57-67)
  • HTTPGetProgramAccsLatencyMetric (96-109)
api/read/bnbsc.py (3)
config/defaults.py (1)
  • MetricsServiceConfig (6-42)
metrics/ethereum.py (8)
  • WSBlockLatencyMetric (145-310)
  • HTTPBlockNumberLatencyMetric (33-43)
  • HTTPEthCallLatencyMetric (14-30)
  • HTTPAccBalanceLatencyMetric (64-79)
  • HTTPDebugTraceBlockByNumberLatencyMetric (82-92)
  • HTTPDebugTraceTxLatencyMetric (95-110)
  • HTTPTxReceiptLatencyMetric (46-61)
  • HTTPGetLogsLatencyMetric (113-142)
metrics/bnbsc.py (7)
  • HTTPBlockNumberLatencyMetric (92-102)
  • HTTPEthCallLatencyMetric (6-22)
  • HTTPAccBalanceLatencyMetric (43-58)
  • HTTPDebugTraceBlockByNumberLatencyMetric (79-89)
  • HTTPDebugTraceTxLatencyMetric (61-76)
  • HTTPTxReceiptLatencyMetric (25-40)
  • HTTPGetLogsLatencyMetric (105-134)
api/read/arbitrum.py (3)
config/defaults.py (1)
  • MetricsServiceConfig (6-42)
metrics/ethereum.py (8)
  • WSBlockLatencyMetric (145-310)
  • HTTPBlockNumberLatencyMetric (33-43)
  • HTTPEthCallLatencyMetric (14-30)
  • HTTPAccBalanceLatencyMetric (64-79)
  • HTTPDebugTraceBlockByNumberLatencyMetric (82-92)
  • HTTPDebugTraceTxLatencyMetric (95-110)
  • HTTPTxReceiptLatencyMetric (46-61)
  • HTTPGetLogsLatencyMetric (113-142)
metrics/arbitrum.py (7)
  • HTTPBlockNumberLatencyMetric (92-102)
  • HTTPEthCallLatencyMetric (6-22)
  • HTTPAccBalanceLatencyMetric (43-58)
  • HTTPDebugTraceBlockByNumberLatencyMetric (79-89)
  • HTTPDebugTraceTxLatencyMetric (61-76)
  • HTTPTxReceiptLatencyMetric (25-40)
  • HTTPGetLogsLatencyMetric (105-134)
api/write/solana.py (2)
config/defaults.py (1)
  • MetricsServiceConfig (6-42)
metrics/solana_landing_rate.py (1)
  • SolanaLandingMetric (49-186)
🔇 Additional comments (5)
api/read/base.py (1)

18-24: Inconsistent region set – deliberate?

Other modules include "sin1" but exclude "kix1"; this file does the opposite. Confirm this asymmetry is intentional, otherwise some regions will emit Base-chain metrics while others do not.

api/read/bnbsc.py (2)

26-39: Region-gated metrics: LGTM

Conditional gating on VERCEL_REGION is clear and aligns with the PR goal.


26-39: No changes needed: MetricsHandler gracefully handles empty METRICS

Verified in common/metrics_handler.py that:

  • handle() resets self._instances = [] when METRICS is empty
  • get_metrics_text() returns an empty string if there are no metric instances
  • handle() then logs a warning (“Nothing to push to Grafana.”) and returns ("done", "") without raising exceptions

All good—no action required.

api/read/arbitrum.py (1)

26-39: Region-gated metrics: LGTM

Pattern matches other read handlers; conditional list keeps the handler wiring simple.

api/write/solana.py (1)

10-14: Region-gated metric: LGTM

Gating the SolanaLandingMetric by VERCEL_REGION aligns with the read-side pattern.

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